Parziphal
Parziphal

Reputation: 6902

Accessing constants using string variable

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

Answers (4)

dario
dario

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

faby
faby

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

Sievajet
Sievajet

Reputation: 3513

This uses reflection:

var value = typeof ( Foo ).GetFields().First( f => f.Name == "FooConst" ).GetRawConstantValue();

Upvotes: 2

Chris
Chris

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

Related Questions