Is it possible to initialize a property at the point of declaration
Imagine you have a field _items in a class. You can initialize it at the point of declaration:
class C
{
IList<string> _items=new List<string>();
}
Now I want to convert this field to an auto generated property, but the initialization is now invalid:
class C
{
public IList<string> Items=new List<string>(); {get; set;} // Invalid
}
So, I have to do:
class C
{
public IList<string> Items {get; set;}
public C
{
Items=new List<string>();
}
}
But this is not nearly as convenient as initializing fields at the point of declaration. Is there a better way to do this, without having to (needlessly) back this property with 开发者_StackOverflow中文版a private (initialized at the point of declaration) field, for example.
Thanks
No, automatic properties don't allow you to set an initial value.
It's annoying, but such is life. (It's annoying that they can't be readonly, too. But that's a rant for another day.)
EDIT: Both readonly automatically implemented properties and specifying an initial value are slated to be in C# 6.
In c#6 you can write something like this:
class C
{
public IList<string> Items {get; set;} = new List<string>();
}
I don't believe so - on construction, as you demonstrate, is the next best way so you don't have to use a private backer, and then use constructor-chaining to ensure that the property always gets initialised:
public MyClass() { PropA = default_Value; }
public MyClass(params object[] args) : this() { /* other code */ }
It would be a nice feature; but then, auto implemented properties are there to simplify property implementation on types; and I can't see how you could add, at the language-level, the default-value feature to an auto-property without the code looking a little, well, odd.
But then, that's why I'm not a language designer.
I'm afraid it is not possible to directly initialize an auto property when you declare it. And I agree that this is a pity. I don't know any better way then the constructor either. See also Initializing C# auto-properties
Nope, this is the only way.
Since you don't declare the field when you use { get; set; }
, you can't specify the initial value.
So you need to declare the field yourself or initialize it in the constructor.
Using a private backing field or setting the value in the constructor are the only ways to give initial values to a Property.
精彩评论