mercredi 30 mai 2018

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?





Aucun commentaire:

Enregistrer un commentaire