If you wanna set properties default value at the time of Class Instance creationg here is code that.
Import following name space to your class with using directives.
Then create a private variable field for property
Finally here is code that generate default value with property.
Note: You can create a DefaultValueAttribute with any value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member.
For more reference see following link - http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
Import following name space to your class with using directives.
using System.Collections.Generic; using System.Text; using System.ComponentModel;
Then create a private variable field for property
private string _message;
Finally here is code that generate default value with property.
[DefaultValue("This is default value of message")] //this code generates default value public string Message { get { return _message; } set { _message = value; } }
Note: You can create a DefaultValueAttribute with any value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member.
For more reference see following link - http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
This example is just outright incorrect. This attribute doesn't do anything other then tell a visual designer what to reset the value to. It doesn't set the value when the class is created.
ReplyDeletecode looks good to me, and to MS ;)
ReplyDeletehttp://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
make sure to add a
using System.ComponentModel; (C#)
> Anonymous #1 said...
ReplyDelete> This attribute doesn't do anything other then tell a visual designer
> what to reset the value to. It doesn't set the value when the class is created.
> Anonymous #2 said...
> code looks good to me, and to MS ;)
> http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
That link states:
> A DefaultValueAttribute will not cause a member to be automatically initialized with the
> attribute's value. You must set the initialvalue in your code.
Anonymous #1 is right, mostly, although the code *could* find the
attribute value and use it to actually set the value initially.
No, its not. Test it yourself.
ReplyDelete[System.ComponentModel.DefaultValue(true)]
public bool MyBool
{get;set;}
will always default to FALSE (a string to null, etc)
Below the MSDN article, there is a link to a KB article that explains why this example is wrong.