Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the name of a constant based on the value

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.

like image 424
Fraser Avatar asked Jun 30 '09 15:06

Fraser


3 Answers

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
}
like image 198
Jon Skeet Avatar answered Nov 11 '22 02:11

Jon Skeet


I may be late.. but i think following could be the answer

public static class Names
    {
        public const string name1 = "Name 01";
        public const string name2 = "Name 02";

        public static string GetName(string code)
        {
            foreach (var field in typeof(Names).GetFields())
            {
                if ((string)field.GetValue(null) == code)
                    return field.Name.ToString();
            }
            return "";
        }
    }

and following will print "name1"

string result = Names.GetName("Name 01");
Console.WriteLine(result )
like image 21
Yohan Avatar answered Nov 11 '22 02:11

Yohan


You may be interested in Enums instead, which can be programmatically converted from name to value and vice versa.

like image 37
foson Avatar answered Nov 11 '22 01:11

foson