开发者

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

This must have been asked many times but I cannot find it....sorr开发者_Go百科y...

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


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


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.


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.


In VS 2017 you can:

    public int Minimum { get; private set; } = 0;
    public int Maximum { get; set; } = 5;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜