Sunday, 30 August 2009

Dissecting ‘Hello World’

Look at the following piece the age old Hello World program in C#.


The above piece of code can be explained as having

  1. Defined a type called Program having a single public static method called Main
  2. Main refers to a type called System.Console which is written by Microsoft and the IL code that implements it is in a file called MsCorLib.dll
  3. To compile the program you could have executed the following statement:
    1. csc.exe /out:Program.exe /t[arget]:exe /r[eference]:MSCorLib.dll Program.cs
  4. But, the following statement also works:
    1. csc.exe Program.cs
  5. Reason being the fact that the compiler has some defaults and reference to MsCorLib.dll is one such default. Please note that MsCorLib.dll is the most critical of all .Net BCLs. It contains all the core types like String, Int32 etc, exe is another default.
  6. However, if you want to beak it try the following:
    1. csc.exe /nostdlib Program.cs
    2. /nostdlib asks the compiler to ignore MsCorLib.dll. If this switch is breaking a simple statement then why is it useful, you might ask.
    3. The reason is simple when the compiler compiles MsCorLib.dll is doesn’t need a reference to MsCorLib.dll does it? It uses the /nostdlib then.

As a result of the above command, a simple executable file called Program.exe is now created. Lets dive a little deeper into it.

  1. It’s a PE (Portable Executable) having the following:
    1. PE header(32/32+)
    2. CLR header
    3. Metadata
      1. To examine the Metadata within a managed PE file use ILDasm.exe
    4. IL
  2. It's also an Assembly.

See you soon!

No comments: