Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Setting a default value for C# Auto-implemented properties

5.00/5 (5 votes)
7 Jan 2012CPOL 17.8K  
While leaving aside the performance penalties, it is a reasonable approach to make code cleaner.Though you can further benefit from the extension methods:public static void InitDefaults(this object o){ PropertyInfo[] props = o.GetType().GetProperties(BindingFlags.Public |...
While leaving aside the performance penalties, it is a reasonable approach to make code cleaner.

Though you can further benefit from the extension methods:

C#
public static void InitDefaults(this object o)
{
    PropertyInfo[] props = o.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

    foreach (PropertyInfo prop in props)
    {
        if (prop.GetCustomAttributes(true).Length > 0)
        {
            object[] defaultValueAttribute =
                prop.GetCustomAttributes(typeof(DefaultValueAttribute), true);

            if (defaultValueAttribute != null)
            {
                DefaultValueAttribute dva = defaultValueAttribute[0] as DefaultValueAttribute;

                if (dva != null)
                    prop.SetValue(o, dva.Value, null);
            }
        }
    }
}


public MyClass()
{
    this.InitDefaults();
} 


Taken from:
Setting Default Values on Automatic Properties[^]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)