Reader Level:
ARTICLE

C# and .NET

Posted by Kamran Articles | C# Language January 07, 2002
It is sometimes important to know the details of what the compiler does. You may want to know whether constants are evaluated at compile time, or whether constant strings are folded at compile time.
  • 0
  • 0
  • 5471

What is MSIL?
 
It is sometimes important to know the details of what the compiler does. You may want to know whether constants are evaluated at compile time, or whether constant strings are folded at compile time. This information can sometimes be found in the C# Language Specification or other documentation, but some of the information isn't there, or is difficult to find. And even if you can find it, it may be tough to understand.

In that case, the easiest thing to do is to compile the code and see what the compiler generates. The SDK contains a tool called the Microsoft Intermediate Language Disassembler (ILDASM) that can disassemble the MSIL to a textual representation, so that you can see the MSIL that is generated when your code is compiled. You can also use ILDASM to view the metadata in an assembly.

To really understand what the MSIL is doing, you'll need to learn MSIL in detail. The stack architecture used by the .NET Common Language Runtime is considerably simpler than the x86 architecture, but there is still a lot to learn to be able to write MSIL.

In most cases, however, you don't need to be able to write MSIL; you just need to be able to read it. Consider the following code, in which we concatenate two static strings.

using System;
class Test
{
public static void Main()
{
Console.WriteLine("Hello " + "world");
}
}

After this is compiled, we can run ILDASM on the output. If we do this, we will see that there's a class named Test, and a static function called Main(). Opening that function yields the following disassembled code:



Even if we know nothing about the .NET MSIL, we can see that there is a single string in the MSIL, and we can therefore deduce that the C# compiler does do the concatenation at compile time. Many questions about the C# compiler-or any other .NET compiler-can be answered the same way.

As many of you have no doubt guessed, you can also point ILDASM at the assemblies that come as part of .NET and look at the information there. This may come in handy when you're trying to figure out how a system component does something, assuming you can understand the MSIL

NOTE: if you are interested in the details of MSIL, you can find the documentation in the Tool Developers Guide/docs directory of the Framework SDK.

COMMENT USING

Trending up