Auto-property initializers

This is one of a series of posts on some of the new features in C# 6.0, which was just released.

Auto-properties were added some time ago. An auto-property lets you define a property without a backing field:

public string MyProperty {get; set;}

While these are extremely useful, if you want to initialize the properties, you generally have to do it in your constructor(s) which might be some way away from your property declaration:

public class MyClass 
{
  public MyClass()
  {
    MyProperty = "Doom";
  }

  public string MyProperty {get; set;}
}

When you have a backing field, the backing field could be initialized at the declaration:

private myField = "Doom";

Well, now you can do the same thing with auto-properties:

public string MyProperty {get; set;} = "Doom";

This keeps the value next to the property, which makes it easier to manage. You can also now create read-only properties that are initialized in the same way:

public string MyProperty {get;} = "Doom";

This isn’t that useful if you are using a constant string (since you could just as easily use a const), but if the value is initialized in a more complex way, this becomes more useful:

public string MyProperty {get;} = GetInitialValue();

Note that GetInitialValue() will have to be a static method – you can’t access instance methods because the class is not yet fully initialized.

Here are links to posts about other new features in C# 6.0:

Tagged with: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*