-3

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.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 1
    STOP ANSWERING. LOOK HERE http://stackoverflow.com/questions/169220/initializing-c-sharp-auto-properties congrats for making 100% duplicate – M.kazem Akhgary Oct 21 '15 at 10:10

1 Answers1

1

This MS Link explains:

Auto-property initializers are now enabled, and are similar to initializers on fields

public class Customer 
{ 
    public string First { get; set; } = "Jane"; 
    public string Last { get; set; } = "Doe"; 
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Michael B
  • 581
  • 1
  • 5
  • 17