112

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";
   }
}
MatteKarla
  • 2,707
  • 1
  • 20
  • 29
Omu
  • 69,856
  • 92
  • 277
  • 407

4 Answers4

199

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

fields[0].GetValue(null)
deczaloth
  • 7,094
  • 4
  • 24
  • 59
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
30

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);
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • For some reason I had to add these flags for it to work: `BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy` – ELIAS YOUSSEF Apr 07 '21 at 23:14
8

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)); 
Pauli Østerø
  • 6,878
  • 2
  • 31
  • 48
  • 1
    Don't trust variable names... the OP is calling GetFields, not GetProperties ;) – Thomas Levesque May 05 '11 at 13:31
  • @PauliØsterø what does the second `null` correspond to? Does not [`FieldInfo.GetValue`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.fieldinfo.getvalue?view=netframework-4.7.2) only accept a single parameter? I can't seem to find overloads of `GetValue` or anything – Thomas Flinkow Jan 16 '19 at 14:07
  • @ThomasFlinkow mere typo, its fixed now – Pauli Østerø Jan 17 '19 at 17:34
  • @PauliØsterø thought so :) just wanted to make sure the code in the question is copy-paste ready. So +1 for a good answer. – Thomas Flinkow Jan 17 '19 at 20:55
5

Try this

FieldInfo fieldInfo = typeof(Settings.Lookup).GetFields(BindingFlags.Static | BindingFlags.Public)[0];
    object value = fieldInfo.GetValue(null); // value = "abc"
Aliostad
  • 80,612
  • 21
  • 160
  • 208