#260 – How Properties Look Under-the-Covers
March 4, 2011 Leave a comment
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.