views:

113

answers:

2

I need like this

public class AA{
   public AA(){}
   [Default("hi")]
   public string value1{get;set}
   [Default(12)]
   public int value2{get;set;}
}

Usage:

AA a=new AA();
print(a.value1);  //result: hi
print(a.value2);  //result: 12

Is it possible to create like this?

I know another way

Public class AA{
   public AA(){value1="hi";value2=12}
   ...
}

Otherwise

AA a=new AA(){value1="hi",value2=12};

But i need only attribute.

+5  A: 

No, but you can easily initialize them in your parameterless constructor.

public class AA
{
   public AA()
   {
      // default values
      Value1 = "hi";
      Value2 = 12;
   }

   public string Value1 {get;set}
   public int Value2 {get;set;}
}

Or, instead of using auto-implemented properties, use actual properties with backing fields initialized to a default value.

public class AA
{
   private string _value1 = "hi";
   public string Value1
   { get { return _value1; } }
   { set { _value1 = value; } }

   private int _vaule2 = 12;
   public int Value2
   { get { return _value2; } }
   { set { _value2 = value; } }
}

Creating a property with an actual backing field is not such a big problem with Visual Studio snippets. By typing prop in VS and hitting the Tab key, you get the full snippet for a read/write property.

[Edit] Check this thread also: How do you give a C# Auto-Property a default value?

[Yet another edit] If your believe this will make it more readable, check the following link: it's a get/set snippet which will generate the property with the necessary backing field, and automatically add a #region block around it to collapse the code: Snippets at CodePlex (by Omer van Kloeten). Download it and check the Get+Set Property (prop) snippet.

Groo
My problem is my class has too many properties
ebattulga
But how is that related to having default values for properties? If your class is a "bunch-of-settings" type of class, then you need to have default values.
Groo
A: 

Not currently. Right now, the only options are to set this in the constructor, or to use a property with a backing field.

However, you could use PostSharp to implement this via AOP fairly easily. (Although, I do not believe this is currently an option).

Reed Copsey