Sunday, October 25, 2015

Minimizing the distance between class property declaration and initialization in auto-backed properties

In C# you can do:
public class Foo1
{
    public string Bar {get; set;}
}

The compiler automatically creates the backing field for the Bar property.
Before this auto-backing syntax sugar you would do this:

public class Foo2
{
private string bar = "";
public string Bar
{
   get {return bar;}
   set {bar = value;}
}
}

Ouch, my fingers hurt from all that extra typing.

This is some nice syntax sugar. However, there's a problem with it. When I heard about this feature and started using it, I incorrectly assumed that the backing field would be initialized to something. Nope! So Foo1 != Foo2. To make Foo1 be equivalent to Foo2 you'd have to initialize bar in the constructor.
public class Foo1Again
{
    public string Bar {get; set;}
    public Foo1Again()
   {
        Bar = "";
    }
}


The problem with this is you might be used to typing the backing field, and incorrectly assume that it's initialized for you. That's when Null Reference exceptions start happening. So if you decide to use auto-backed properties, you need to remember to init in the constructor. Ouch... I'd rather stick with typing out the backing field myself, so I don't randomly forget to initialize the field.

However, in C#6 they solved this, and you can now initialize the property inline with the declaration!!
See this: http://stackoverflow.com/a/169872/1538717

public class FooCharp6
{
    public string Foo {get;} = "";

}
   





No comments:

Post a Comment

There was an error in this gadget