I'd like to write a procedure in which i can pass the constant name as
a string and be able to retrieve the constant value. for instance
//method definition
public int getConst( string constName ){...}
//usage
int x = getConst( "XVALUE" );
I assume i can use reflection to do this. Can someone tell me how
please?
(The reason i want to do this is that i want to use the constant name
in a properties file rather than the value)
thank you
using System;
using System.Reflection;
public class Constants
{
public const int XValue = 10;
public const int YValue = 20;
public const int ZValue = 30;
}
class Test
{
static void Main()
{
Console.WriteLine (GetConst("XValue"));
Console.WriteLine (GetConst("YValue"));
}
static object GetConst (string name)
{
FieldInfo field = typeof (Constants).GetField
(name,
BindingFlags.Static |
BindingFlags.Public);
return field.GetValue(null);
}
}
--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Yes. Note that I renamed your constants to fit in with the .NET naming
convention. You don't have to do that, but I'd recommend it :)
1. Is it possible to use this mechanism to retrieve Enum constants?
2. Is it possible to do the reverse, that is given an int value,
retrieve the string representation of the constant that represents that
int value?
thanks much for your help!
static object GetConst (string name)
{
FieldInfo field = typeof (Constants.MyEnumName).GetField
(name,
BindingFlags.Static |
BindingFlags.Public);
return field.GetValue(null);
}
Still not sure how to do #2 however.
<snip>
> 2. Is it possible to do the reverse, that is given an int value,
> retrieve the string representation of the constant that represents that
> int value?
Well, if you know all the places that constant could live, you can find
all the fields (using GetFields), fetch all the values and find out
which is equal to the value you've got. Just be aware that you could
easily have multiple fields with the specified value.