C# Hello World Example

C# is the newest enterprise programming language created by Microsoft to compete with Java. Let's start with the classic Hello World example.

C# Hello World code

At first glance, the C# Hello World example is very similar with Java, as the code below shows.

 
using System;
 
class Test
{
  static void Main() {
    Console.WriteLine("Hello World");
    Console.WriteLine(add(3,4));
  }
 
  static int add(int x, int y) {
    return x + y;
  }
}
 

It has a class name, a void main method, even the namespace looks similar, in Java it will be package and keyword is import.

The Console.WriteLine is similar with System.out.println.

Compile and run the example

We will compile and run the example from the Developer Command Prompt cmd window that installed with Visual Studio.

The prompt will prepare all the settings for compiling. Execute csc with the file name as parameter.

It will generate an executable file. Unlike Java in which you get a class file that contains byte code and executed in JVM. C# generate code can directly run on your machine.

But the exe generated by C# compiler is different from files generated by a C++ compiler. It's a CLR exe.

The CLR exe contains CLR header and IL code which is the byte code used in C#. At runtime, the IL code will be converted to native code by CLR.

C# executable still needs the virtual machine, but the virtual machine is integrated into Windows and pretend like the native executable.

The CLR exe contains code that will show a dialog in case the CLS is not installed.