Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no initial values on {get;set;} accessors (VS 2010 C#)

This must have been asked many times but I cannot find it....sorry...

Why is the following not permitted?

public string MyString = "initial value" {get; private set;}

(Visual C# Express 2010)

like image 631
Paulustrious Avatar asked Dec 22 '22 01:12

Paulustrious


2 Answers

It's just not valid syntax. You can't initialize the value of an auto-property, unfortunately.

The best options are to either make the property manually:

private string _MyString = "initial value";
public string MyString { get { return _MyString; } set { _MyString = value; } }

or initialize the value in the constructor:

public string MyString { get; set; }

....

public MyClass() {
    MyString = "initial value";
}
like image 199
MisterZimbu Avatar answered Jan 10 '23 11:01

MisterZimbu


An alternative:

string _strMyString;

public string MyString
{
    get {
        if (String.IsNullOrEmpty(_strMyString) {
             return "initial value";
        } else { 
             return _strMyString; 
        }
}
like image 24
Chuck Callebs Avatar answered Jan 10 '23 09:01

Chuck Callebs