How to get the default value of an object property?

Wex picture Wex · Feb 16, 2010 · Viewed 7.1k times · Source

Some code:

foreach (System.Reflection.PropertyInfo pi in myObject.GetType().GetProperties())
{
    if (pi.CanWrite)
    {
        object value = pi.GetValue(Properties, null);

        // if (value is not default)
        // {
        X.addAttribute(pi.Name, value);
        // }
    }
}

What I'm trying to do is not-call the line 'X.addAttribute...' if the property is at its DefaultValue. I assume there's some way of getting the DefaultValue of a property so I can do a comparison?

For my purpose I am trying to get the 'default' value as defined by DefaultValueAttribute.

Any help is appreciated, cheers.

Answer

mythz picture mythz · Feb 16, 2010

Below is the method I use to get a default value of any runtime-type it will return 'null' for non value types otherwise it will return the default value type (it includes caching of value types for extra perf):

private static readonly Dictionary<Type, object> DefaultValueTypes 
    = new Dictionary<Type, object>();

public static object GetDefaultValue(Type type)
{
    if (!type.IsValueType) return null;

    object defaultValue;
    lock (DefaultValueTypes)
    {
        if (!DefaultValueTypes.TryGetValue(type, out defaultValue))
        {
            defaultValue = Activator.CreateInstance(type);
            DefaultValueTypes[type] = defaultValue;
        }
    } 

    return defaultValue;
}