Omu
Omu

Reputation: 71206

Get value of a public static field via reflection

This is what I've done so far:

 var fields = typeof (Settings.Lookup).GetFields();
 Console.WriteLine(fields[0].GetValue(Settings.Lookup)); 
         // Compile error, Class Name is not valid at this point

And this is my static class:

public static class Settings
{
   public static class Lookup
   {
      public static string F1 ="abc";
   }
}

Upvotes: 118

Views: 91573

Answers (4)

Thomas Levesque
Thomas Levesque

Reputation: 292455

You need to pass null to GetValue, since this field doesn't belong to any instance:

fields[0].GetValue(null)

Upvotes: 208

Pauli Østerø
Pauli Østerø

Reputation: 6916

The signature of FieldInfo.GetValue is

public abstract Object GetValue(
    Object obj
)

where obj is the object instance you want to retrieve the value from or null if it's a static class. So this should do:

var props = typeof (Settings.Lookup).GetFields();
Console.WriteLine(props[0].GetValue(null)); 

Upvotes: 8

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64933

You need to use Type.GetField(System.Reflection.BindingFlags) overload:

For example:

FieldInfo field = typeof(Settings.Lookup).GetField("Lookup", BindingFlags.Public | BindingFlags.Static);

Settings.Lookup lookup = (Settings.Lookup)field.GetValue(null);

Upvotes: 33

Aliostad
Aliostad

Reputation: 81660

Try this

FieldInfo fieldInfo = typeof(Settings.Lookup).GetFields(BindingFlags.Static | BindingFlags.Public)[0];
    object value = fieldInfo.GetValue(null); // value = "abc"

Upvotes: 7

Related Questions