tags:

views:

44

answers:

2

I have a public attribute in some class. I want a default value -1 for this attribute without an private variable like _MyAttr(because too many attributes, i won't add them one by one).

public int MyAttr { get; set; }

[DefaultValueAttribute] is not working for this issue i think. Any ideas? Thanks.

A: 

Just set a this.MyAttr = -1 assignment in the object's constructor.

Jon Limjap
+3  A: 

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.

womp
No other way to make a default value? You know I really want an expression like this :(public int MyAttr = -1 { get; set; }
Danny Chen
Danny, that kinda defeats the purpose of automatic properties. Seriously.
Jon Limjap