I have a public property in some class. I want a default value -1 for this property without an private variable like _MyField(because too many properties in this class, i won't add them one by one).
public int MyProperty { get; set; }
[DefaultValueAttribute] is not working for this issue i think. Any ideas? Thanks.
UPDATE @ Aug 2015 Now we have C# 6!
public int MyProperty { get; set; }开发者_StackOverflow社区 = 100;
public string EasyToUse { get; } = "YES!";
You basically have two options - you can set the property in the constructor of the object, or use a private field.
Personally, I feel the constructor is the best option, as it's clear to people reading your code what your intentions are for a fresh instance of your class.
[DefaultValue]
is an attribute meant for use with visual designer functionality, and has no effect on your class logic.
Just set a this.MyAttr = -1
assignment in the object's constructor.
精彩评论