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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.