Search code examples
c#initializationautomatic-properties

Initializing C# auto-properties


I'm used to writing classes like this:

public class foo {
  private string mBar = "bar";
  public string Bar {
    get { return mBar; }
    set { mBar = value; }
  }
  //... other methods, no constructor ...
}

Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?

public class foo2theRevengeOfFoo {
  //private string mBar = "bar";
  public string Bar { get; set; }
  //... other methods, no constructor ...
  //behavior has changed.
}

You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.

Something like this would make more sense to me:

public string Bar { get; set; } = "bar";

Solution

  • Update - the answer below was written before C# 6 came along. In C# 6 you can write:

    public class Foo
    {
        public string Bar { get; set; } = "bar";
    }
    

    You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):

    public class Foo
    {
        public string Bar { get; }
    
        public Foo(string bar)
        {
            Bar = bar;
        }
    }
    

    It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)

    Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.

    This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.