Thursday, March 1, 2007

How to set default value of a property in Class-C# 2.0

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.

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
Share:

4 comments:

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

    ReplyDelete
  2. code looks good to me, and to MS ;)
    http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

    make sure to add a
    using System.ComponentModel; (C#)

    ReplyDelete
  3. > Anonymous #1 said...
    > 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.

    ReplyDelete
  4. No, its not. Test it yourself.

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

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews