About Me

My photo
Kozyatağı, İstanbul, Türkiye

Sunday, March 17, 2013

Printing "Hello World" Without Using Semicolon (;)


This is an old question which has been asked C beginners. Actually, C code for “printing Hello World without using semicolon” is substantially easier than C# code. Here it is:
C Code:
#include <stdio.h>

void main(void)
{
 if (printf("Hello World"))
 {
 }
}

The main advantage here is that printf function returns a value, it is not void. However, Console.WriteLine function of C#, which is equivalent to printf of C, does NOT return a value. It is void.
So the question becomes, “How can I invoke WriteLine method of Console class so that the invocation returns a value?”.

The answer is “reflection”.  .NET refleciton library is quite robust for handling runtime metadata retrieveing, dynamic method invocation. Here, we need to use “MethodInfo” class, which represents a funciton of a class. MethodInfo has an “Invoke” function, which returns object!

Here is the code:

C# Code:
namespace nameSpaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            if (
                    typeof(System.Console).
                    GetMethod(
                            "WriteLine", new SystemType[] { typeof(string) })
                    .Invoke(
                        null,
                        new string[] { "Hello World!" })
                     == null
                )
            {

            }
        }
    }
}

No comments:

Post a Comment