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

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

Posted by jalpesh vadgama |  March 01, 2007 |  C#.NET |  4 comments    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