Reputation: 1110
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"?
Upvotes: 5
Views: 3813
Reputation: 14700
A good solution would be to combine the Reflection option that Amir Popovich and Marcin Juraszek suggested to retrieve the constant value-name relationship via code, with Noctis' suggestion to build an Enum automatically out of it.
If this isn't code that changes often (which I understand is the case) than dynamically building a value-name dictionary and accessing it at runtime has more overhead than statically creating an enum and including it in your project.
Add it as a build step and move the processing time to the compiler, rather than the runtime.
Upvotes: 0
Reputation: 29836
Keep it simple using reflection:
var props = typeof(Manufacturer).GetFields(BindingFlags.Public | BindingFlags.Static);
var wantedProp = props.FirstOrDefault(prop => (ushort)prop.GetValue(null) == 6);
Upvotes: 6
Reputation: 11763
One option might be to write a script that takes that class as a parameter, and creates an Enum
class. (so basically, changes the class header to enum, chops the crap before the company name, and change the ;
to ,
for all but the last one.
Then you can just use that enum with the value you have.
Upvotes: 1
Reputation: 172458
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
Upvotes: 2