65.9K
CodeProject is changing. Read more.
Home

Setting a default value for C# Auto-implemented properties

starIconstarIconstarIconstarIconstarIcon

5.00/5 (5 votes)

Jan 4, 2012

CPOL
viewsIcon

17909

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:
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[^]