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)
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";
}
An alternative:
string _strMyString;
public string MyString
{
get {
if (String.IsNullOrEmpty(_strMyString) {
return "initial value";
} else {
return _strMyString;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With