views:

77

answers:

5

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)

+1  A: 

It's a property, not a field. You can't initialize it this way. Just set the value in the constructor.

Steven Sudit
+3  A: 

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";
}
MisterZimbu
+1  A: 

An alternative:

string _strMyString;

public string MyString
{
    get {
        if (String.IsNullOrEmpty(_strMyString) {
             return "initial value";
        } else { 
             return _strMyString; 
        }
}
treefrog
String.IsNullOrEmpty
Tergiver
I always forget about that method.
treefrog
+1  A: 

the syntax

public string MyString { get; set; }

is replacing the old style / annoying / trivial (as of vs2008/c# 3.0 you can see all the new features of c# 3.0 here)

private string _MyString;

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

the compiler is actually generates a member before compiling your code. you can open a reflector and see the generated member.

Itai Zolberg
A: 

Why?

I cannot speak on behalf of the designers of C#, but I can make educated speculation:

  1. They wanted to see just how big of a deal it is before taking the time to add another feature and yet another rule to the language.
  2. They could not find a sufficiently elegant-looking way to do this.

That said, here is how I would allow values (when a set accessor is available, of course):

public string MyProp {get;set;} = "initial value"; // not valid C#

Without making the language any more complex, they could write the rule so that it applies to "[all] properties with set accessors" instead of to "default properties with set accessors":

// again, not valid C#:
public string MyProp
{
    get { return _MyProp;}
    set { _MyProp = value; }
} = "initial value before being massaged or rejected by the set accessor.";

The only downside I see here is that it is ugly. The benefits are that you can concisely specify an initial value for a property with that property instead of in the constructor, and that you can let the value be massaged / checked / whatever via constructor at runtime if you wish.

apollodude217