Wednesday, July 6, 2016

How to set default value to auto properties in C#?

There are many ways to initialize properties with default value. The most common way to set default value of any property is to set its local variable with default value. See below example.

Code –
public partial class DefaultValueProperties : Window
{
    private int age = 25;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public DefaultValueProperties()
    {
        InitializeComponent();

        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }

}

Output –
Age - 25

But when you are using auto-properties you don’t need to declare local variable for it since it’s internally taken care by CLR. So how to set default value to auto-properties? There is a way, you can set default value to auto-property using DefaultValue attribute. DefaultValue attribute is part of System.ComponentModel namespace. See below example.

Code –
public partial class DefaultValueProperties : Window
{
    //DefaultValue Attribute to set Default Value of Age property
    [DefaultValue(35)]
    public int Age { get; set; }

    //Constructor
    public DefaultValueProperties()
    {
        InitializeComponent();

        //This method sets value for all the properties reading from DefaultValue attribute
        InitializeDefaultProperties(this);
           
        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }

    public static void InitializeDefaultProperties(object obj)
    {
        foreach (PropertyInfo prop in obj.GetType().GetProperties())
        {
            foreach (Attribute attr in prop.GetCustomAttributes(true))
            {
                if (attr is DefaultValueAttribute)
                    prop.SetValue(obj, ((DefaultValueAttribute)attr).Value, null);
            }
        }
    }
}

Output –
Age - 35

As you can see in above example, Age property is decorated with DefaultValue attribute. DefaultValue attribute will not automatically set Property value. You need to manually set its value in constructor using refection. The good part of initializing value of property using Default Value is more consistent with design and less error prone. Since this approach involves reflection, this is not very efficient way to set default value to properties.

With C# 6.0, you can set default value to auto-properties even more better and easiest way. See below code.

Code - 
public partial class DefaultValueProperties : Window
{
    public int Age { get; set; } = 30;

    //Constructor
    public DefaultValueProperties()
    {
        InitializeComponent();

        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }
}

Output –
Age - 30


Hope you liked this article. Your feedback/comments are most welcome. Happy reading. J


References –

See Also –


1 comment: