Desugaring auto-implemented properties

2013-10-08    

What do you prefer: a field or a property? Most object oriented gurus will tell you that a property should be preferred. But do you sometimes feel that writing all those properties in C# is a waste of time?

Of course you know that using properties is important to encapsulate the inner workings of your class. By using accessors and mutators you hide the implementation details of your class and you can add logic like validation or notifications. If you would convert a field to a property you would change the metadata of your assembly and depending applications would have to be recompiled.

But most of your properties have empty getters and setters, but still you have to create a private field and a property with both a get and set accessor like this:

class Foo
{
    private int _bar;

    public int Bar
    {
        get { return _bar; }
        set { _bar = value; }
    }
}

When looking at your Foo class in Ildasm you see the following:

Foo class in ildasm

As you can see, your property is emitted as getBar_ and setBar_ method. This is how your property actually works. Every place where you read from a property is replaced by a call to getBar. Writing is replaced with _setBar. So here you see an example of syntactic sugar! Instead of having to write the _getBar_ and setBar_ method yourself, the compiler helps you by offering a nice syntax for properties.

Going auto

This is all nice, but what if you don’t have to add any extra code to the getter or setter? This is where auto-implemented properties show their value. An auto-implemented property is syntactic sugar that allows you to write a plain property in a simple way:

class Foo
{
    public int Bar { get; set; }
}

You can specify different accessibility levels for your get and set method, for example by marking the setter as read-only:

public int Bar { get; private set; }

As you can see, you don’t have to specify a backing field and you don’t have to write the code for the getter and setter. This is all nice, but how does it work behind the scenes?

Using Ildasm on auto-implemented properties

We can inspect the IL that’s being generated by using Ildasm on the Foo class. This gives you the following result:

Auto generated backing field in ildasm

You still have the getBar_ and setBar_ method but now you also have a kBackingField_ field. In C# this would be an illegal name for a field but in IL code it’s perfectly legal. The compiler uses this naming convention to make sure that generated fields don’t conflict with any user defined elements. It also decorates the field with the CompilerGeneratedAttribute. You can verify that this field really exists by using reflection:

Foo foo = new Foo();
Console.WriteLine(foo.Bar); // Displays 0

var fields = foo.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
var field = fields[0];

Console.WriteLine(field.Name); // <Bar>k_BackingField

field.SetValue(foo, 42);

Console.WriteLine(foo.Bar); // Displays 42

As you can see, the field really exists and when you know it’s name you can even access it through reflection. Of course this isn’t a recommended way to start juggling with your auto-implemented properties. Normally, the backing field of an auto-implemented property is not accessible from your C# code. This also explains why an auto-implemented property requires both a getter and a setter. Since you can’t access the backing field from normal code, it would be useless to have an auto-implemented property with only a getter.

So that’s how auto-implemented properties work. By using them, you get a syntax that’s almost as concise as using a field but offers you the possibility of switching to a full property whenever you want. And by desugaring your code, you discovered that an auto-implemented property is just a get and set method with a private backing field.

Questions? Remarks? Please leave a comment!