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[
^]
I was born in Ukraine. After completing the university degree worked there as a Research Chemist. Last 23 years I live in Australia where I've got my second qualification as a Software Engineer.
"I am the lucky one: I do enjoy what I am doing!"