Behind the Scenes Look at C#: Properties continued
(Page 1 of 4 )
We will continue our discussion covering C# properties. We will cover the MSIL code that the compiler generates when you define a C# property, read-only, write-only properties, and static properties. This article is the fourth in a series covering C#.
MSIL Code and Properties
To discuss the generated MSIL code I will modify the worker example to a simpler version, so we can concentrate on one property and see what's going on with the MSIL code. Copy the following code and compile it, then load the application with the Ildasm.exe tool.
using System;
namespace property
{
class Class1
{
static void Main(string[] args)
{
Worker person = new Worker();
person.Name = "Michael";
Console.WriteLine(person.Name);
}
}
public class Worker
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
}
Navigate to the worker class in the generated MSIL code.

It's clear that we have a property called Name, but why do we have two more methods (get_Name and set_Name)? Actually, the C# compiler generates a property along with its associated get_propertyName and set_propertyName methods, which read and write the value from/to the private field. You may ask yourself, why does the compiler generate a property while it has already been generated -- the get and set methods? Why do we need the property then?
Actually, the runtime doesn't know about the C# construction property. The runtime has a complete knowledge of methods, and as you will see shortly, the compiler determines when to call the method get_Name and the method set_Name each time you read and write with the property. We need the property construction for reflection; for now think of reflection as a way to get information about a loaded object in run time. Now, let's look at the Name property.
Next: The Name Property >>
More C# Articles
More By Michael Youssef