Get value of constant by name

21,237

Solution 1

To get field values or call members on static types using reflection you pass null as the instance reference.

Here is a short LINQPad program that demonstrates:

void Main()
{
    typeof(Test).GetField("Value").GetValue(null).Dump();
    // Instance reference is null ----->----^^^^
}

public class Test
{
    public const int Value = 42;
}

Output:

42

Please note that the code as shown will not distinguish between normal fields and const fields.

To do that you must check that the field information also contains the flag Literal:

Here is a short LINQPad program that only retrieves constants:

void Main()
{
    var constants =
        from fieldInfo in typeof(Test).GetFields()
        where (fieldInfo.Attributes & FieldAttributes.Literal) != 0
        select fieldInfo.Name;
    constants.Dump();
}

public class Test
{
    public const int Value = 42;
    public static readonly int Field = 42;
}

Output:

Value

Solution 2

string customStr = "const1";

if ((typeof (ConstClass)).GetField(customStr) != null)
{
    string value = (string)typeof(ConstClass).GetField(customStr).GetValue(null);
}
Share:
21,237
demo
Author by

demo

.net

Updated on July 09, 2022

Comments

  • demo
    demo almost 2 years

    I have a class with constants. I have some string, which can be same as name of one of that constants or not.

    So class with constants ConstClass has some public const like const1, const2, const3...

    public static class ConstClass
    {
        public const string Const1 = "Const1";
        public const string Const2 = "Const2";
        public const string Const3 = "Const3";
    }
    

    To check if class contains const by name i have tried next :

    var field = (typeof (ConstClass)).GetField(customStr);
    if (field != null){
        return field.GetValue(obj) // obj doesn't exists for me
    }
    

    Don't know if it's realy correct way to do that, but now i don't know how to get value, cause .GetValue method need obj of type ConstClass (ConstClass is static)

  • Jamie Rees
    Jamie Rees over 8 years
    Are you going to explain your code and how this fixes the issue?
  • Lee Dale
    Lee Dale over 8 years
    No not really it's quite self explanatory. The OP asked how to get the value of the const variable and that is the answer.
  • vynsane
    vynsane about 6 years
    string customStr = "const1"; does not include the 'const' keyword, therefore it is not a constant variable. As such, self-explanatory or not, this is not an answer to the question.
  • demo
    demo almost 5 years
    @vynsane, customStr contains name of constant, value of which is needed.
  • Jim Fell
    Jim Fell almost 5 years
    This was of great help, but I had to tweak it some because my function passes in a Type parameter. My implementation looks something like (myPassedType as Type).GetField("Value").GetValue(null).