C# 6.0 Suggestion: Backing Field Type Declaration

This is the third post which expands on two that I have already done tonight. The first was on adding an automatic property initializer syntax to C#, and the second was on adding backing field access from within the property accessors without having to separately specify the backing field.

My next suggested improvement is really just here for the purposes of completeness. Often you want to delay the creation of a backing filed instance until it is accessed. However, if you want to have a backing field which varies in type to the declared property then you need a way to specify the type of the backing field without actually instantiating it. Here is an example of the proposed syntax:

public class Customer
{
  public IEnumerable<Address> Addresses
  {
    get(field)
    {
      if (field == null) field = new Collection<Address>();
      return field;
    }
  } as Collection<Address>();
}

This code is pretty straight-forward. The backing field for the Addresses property is a Collection<Address>, but it is presented as an IEnumerable<Address>, and construction is deferred until it is accessed for the first time.

Potentially the syntax for optional arguments could be “borrowed” here to lead to a more concise syntax:

public class Customer
{
  public IEnumerable<Address> Addresses { get(field = new Customer<Address>()) }
}

In this case the type of the backing field could be inferred, the difference between the two being that the above syntax defers execution of the backing field initialization until the get accessor is called and the example from my automatic property initializer example is executed upon construction.

One thought on “C# 6.0 Suggestion: Backing Field Type Declaration

  1. Pingback: C# 6.0 Suggestions: Quick Review | Mitch Denny

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s