Skip to main content
  1. Posts/

C# Language request for properties

··2 mins

Auto-implemented properties are great, until you need to implement custom get or set logic. I love the ability to make the field an implementation detail, until you need to implement the property. What if you could continue to hide the field, like this:

public string FirstName {
  get {
    // do more stuff, like lazy init the field
    if (field == null)
      field = "Unknown";
    return field;
  }
  set {
    field = value;
  }
}

A new keyword, field, references the compiler-generated property’s backing field. Also, for readonly fields:

public readonly string Id {
  get {
    return field;
  }
  set { // private is implied
    // do more stuff, like don't accept null
    if (value == null)
      value = string.Empty;
    field = value;
  }
}

Where the property would need to be set in the constructor (like read-only fields) as the backing field would be marked read-only. For simplicity, the implementation would use simple property syntax while the compiled output would involve a read-only field, a truly read-only property, and a constructor that executes the property’s set body via a static method call each time the field is set in the constructor.

Please rate and validate this suggestion at the MSDN Microsoft Product Feedback Center.

This proposal was eventually implemented in C# 13 (.NET 9) as the field keyword for semi-auto properties.
George Tsiokos
Author
George Tsiokos

Leave a comment

Preview

Comments are reviewed before publishing.