Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a constant's name given its value

Tags:

c#

A firmware manufacturer is shipping an API every now and then that contains a class like this:

public static class Manufacturer 
{
  public const ushort FooInc = 1;
  public const ushort BarInc = 2;
  public const ushort BigCompany = 3;
  public const ushort SmallCompany = 4;
  public const ushort Innocom = 5;
  public const ushort Exocomm = 6;
  public const ushort Quarqian = 7;
  // snip... you get the idea
}

I have no control over this class, and there is likely to be a new one from time to time, so I don't really want to rewrite it.

In my code I have access to an integer from a data file that indicates the "Manufacturer" of the device that the file came from.

I'd like, if possible, to display the name of the manufacturer on my UI, instead of the number, but the only cross reference I can find is this class.

So, given I have the number "6" from the file, how can I turn that into the text "Exocomm"?

like image 765
dylanT Avatar asked Jan 11 '23 00:01

dylanT


2 Answers

Keep it simple using reflection:

   var props = typeof(Manufacturer).GetFields(BindingFlags.Public | BindingFlags.Static);
   var wantedProp = props.FirstOrDefault(prop => (ushort)prop.GetValue(null) == 6);
like image 145
Amir Popovich Avatar answered Jan 19 '23 00:01

Amir Popovich


You may try like this:

public string FindName<T>(Type type, T value)
{
    EqualityComparer<T> c = EqualityComparer<T>.Default;

    foreach (FieldInfo  f in type.GetFields
             (BindingFlags.Static | BindingFlags.Public))
    {
        if (f.FieldType == typeof(T) &&
            c.Equals(value, (T) f.GetValue(null)))
        {
            return f.Name; 
        }
    }
    return null;
}

Also check C#: Using Reflection to get constant values

like image 27
Rahul Tripathi Avatar answered Jan 19 '23 00:01

Rahul Tripathi