Determine the name of a constant based on the value

.net, c#, constants, reflection

Solution

In general, you can't. There could be any number of constants with the same value. If you know the class which declared the constant, you could look for all public static fields and see if there are any with the value 0, but that's all. Then again, that might be good enough for you - is it? If so...

public string FindConstantName<T>(Type containingType, T value)
{
    EqualityComparer<T> comparer = EqualityComparer<T>.Default;

    foreach (FieldInfo field in containingType.GetFields
             (BindingFlags.Static | BindingFlags.Public))
    {
        if (field.FieldType == typeof(T) &&
            comparer.Equals(value, (T) field.GetValue(null)))
        {
            return field.Name; // There could be others, of course...
        }
    }
    return null; // Or throw an exception
}

Problem

Is there a way of determining the name of a constant from a given value? For example, given the following: public const uint ERR_OK = 0x00000000; How could one obtain "ERR_OK"? I have been looking at refection but cant seem to find anything that helps me.

Original source