What is the magic that makes properties work with the CLR?

c#, clr, syntactic-sugar

Solution

If you look at the IL, you'll find something like this:

.property instance string Source()
{
    .get instance string System.Exception::get_Source()
    .set instance void System.Exception::set_Source(string)
}

.method public hidebysig specialname newslot virtual 
    instance string get_Source () cil managed 
{
    ...
}

.method public hidebysig specialname newslot virtual 
    instance void set_Source (
        string 'value'
    ) cil managed 
{
    ...
}

So the 'magic' is a `.property` member which glues two methods together.

Problem

I noticed when I reflect into an assembly, calls to property accessors sometimes look like methods ``` // "Reflected" example class Class1 { public bool Boolean { get; set;} } class Class2 { public Class2() { var class1 = new Class1(); var boolean = class1.get_Boolean(); } } ``` Now I was curious, and I put a method with a similar signature in `Class1` that looks like the standard convention for accessors. ``` // "Hacked" example class Class1 { public bool get_Boolean() { return true; } } ``` Somehow, the C# compiler still treats `get_Boolean` as a method. What's the magic sauce to get a method to be a property?

Original source