Reputation: 6902
I'm working on Unity, using C#, and I made up a script that would make my life simpler if I could access constants using string variables.
public class Foo
{
public const string FooConst = "Foo!";
public const string BarConst = "Bar!";
public const string BazConst = "Baz!";
}
// ...inside some method, somewhere else
public string Bar(string constName)
{
// is it possible to do something like this?
// perhaps with reflections?
return Foo.GetConstant(constName);
}
My only solution was to create a method that gets the constant inside a switch
. But every time I add a new constant, I have to modify that switch
.
Fun fact: I'm a PHP kid that moved into C#. I like it is pretty strict, strong-typed and stuff... but that also makes things unnecessarily complicated.
Upvotes: 0
Views: 721
Reputation: 5259
Yes, you have to use Reflection. Like this:
public string Bar(string constName)
{
Type t = typeof(Foo);
return t.GetField(constName).GetValue(null));
}
Upvotes: 1
Reputation: 7558
you could try in this way with reflection
var constExample= typeof(Foo).GetFields(BindingFlags.Public | BindingFlags.Static |
BindingFlags.FlattenHierarchy)
.Where(fi => fi.IsLiteral && !fi.IsInitOnly && fi.Name==constName).FirstOrFefault();
where constName
is the constant that you are looking for
Refere here for documentation about property of FieldInfo.
As you can see I have filtered for IsLiteral
= true and IsInitOnly
= false
IsLiteral
: Gets a value indicating whether the value is written at compile time and cannot be changed.
IsInitOnly
: Gets a value indicating whether the field can only be set in the body of the constructor.
Upvotes: 1
Reputation: 3513
This uses reflection:
var value = typeof ( Foo ).GetFields().First( f => f.Name == "FooConst" ).GetRawConstantValue();
Upvotes: 2
Reputation: 5514
You could certainly do that using reflection, but IMHO a better option would be to store the constants in a dictionary or some other data structure. Like so:
public static class Foo
{
private static Dictionary<string,string> m_Constants = new Dictionary<string,string>();
static Foo()
{
m_Constants["Foo"] = "Hello";
// etc
}
public static string GetConstant( string key )
{
return m_Constants[key];
}
}
public string Bar( string constName )
{
return Foo.GetConstant( constName );
}
Obviously this is a simplification. And it would throw an exception if you pass a key that doesn't exists etc.
Upvotes: 1