#260 – How Properties Look Under-the-Covers

The typical pattern for implementing a property in a C# class is shown below–you define a private backing variable in which to store the property value, as well as get and set accessors that read/write the property value.

    public class Dog
    {
        // An typical instance property
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }

We can use the IL DASM tool to take a look at how this property is actually implemented.  Start up the IL Disassembler tool and then do a File | Open and load the .exe containing the property shown above.  You’ll see the following:

We see our private backing variable–name–as well as two methods that represent the get/set accessors–get_Name and set_Name. These are the methods that the compiler generates, which implement the accessors.

Advertisement

#11 – Examine IL Using Ildasm.exe

In .NET, source is compiled to an platform-neutral intermediate language called Common Intermediate Language.  The IL is later compiled into native code at runtime, running in a virtual machine.

You can examine the IL for your applications by running a tool called the IL Disassembler (ildasm.exe).  You can find ILDasm in a directory that looks something like this:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64

Alternatively, you can just type “ildasm” in the Start Menu search box in Windows 7 or Windows Vista.

ILDasm will show you three basic things:

  • A list of all classes and methods in your assembly
  • The contents of the assembly’s manifest
  • IL code for any method implemented in the assembly.

Here’s an example of what is displayed in ILDasm.