Initializing C# auto-properties [duplicate]

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";

4 Answers
4

Leave a Comment