Get the value of an open static field through reflection

This is what I have done so far:

var props = typeof (Settings.Lookup).GetFields(); Console.WriteLine(props[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"; } } 
+72
c #
May 05 '11 at
source share
4 answers

You need to pass null to GetValue , since this field does not belong to any instance:

 props[0].GetValue(null) 
+125
May 05 '11 at 13:24
source share

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

For example:

 FieldInfo field = typeof(Settings.Lookup).GetField("Lookup", BindingFlags.Public | BindingFlags.Static); Settings.Lookup lookup = (Settings.Lookup)field.GetValue(null); 
+11
May 5 '11 at
source share

Signature FieldInfo.GetValue

 public abstract Object GetValue( Object obj ) 

where obj is the instance of the object from which you want to get the value or null if it is a static class. So what this should do:

 var props = typeof (Settings.Lookup).GetFields(); Console.WriteLine(props[0].GetValue(null)); 
+4
May 05 '11 at 1:26
source share

try it

 FieldInfo fieldInfo = typeof(Settings.Lookup).GetFields(BindingFlags.Static | BindingFlags.Public)[0]; object value = fieldInfo.GetValue(null); // value = "abc" 
+4
May 05 '11 at 13:27
source share



All Articles