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";
   }
}

Solution 1:

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

fields[0].GetValue(null)

Solution 2:

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

  • http://msdn.microsoft.com/en-us/library/4ek9c21e.aspx

For example:

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

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