Search code examples
c#reflectionenumsdefault

How to get default value of an enum from a type variable


Given an object (unknown at design time), I loop on its properties to do some processes. On each property, I have to check whether its value is different from the default value or not.

foreach(var p in propertyInfos)
{
    if (something) { ... }
    else if (p.PropertyType.IsEnum)
    {
        object oDefault = GetDefaultValueOfThisPropertyByWhateverMethod();
        if (oDefault == null)
            oDefault = default(p.PropertyType); // not valid
        var vValue = p.GetValue(myObject);

        if (!oDefault.Equals(vValue))
            // Do something enum specific when value is not the default one.
    }
}

How could I achieve this, knowing that there may exist enums that do not containt items with value 0?


Solution

  • The default value of an enum is 0... Even if there is no value defined for 0. In the end you can always (EnumType)123 for any enum. enum don't check/restrict their "valid" values. Only give some labels to some specific values.

    Note that the 0 I spoke before is a "typed" value... So it is (EnumType)0, not a (int)0... You can:

    object oDefault = Enum.ToObject(p.PropertyType, 0);
    

    Works even with non-int based enums, like:

    enum MyEnum : long
    {
    }
    

    Clearly you could even:

    object oDefault = Activator.CreateInstance(p.PropertyType);
    

    because new SomeEnumType() is 0.