Get value of a public static field via reflection

C#.Net

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

fields[0].GetValue(null)

Solution 2 - C#

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);

Solution 3 - C#

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)); 

Solution 4 - C#

Try this

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOmuView Question on Stackoverflow
Solution 1 - C#Thomas LevesqueView Answer on Stackoverflow
Solution 2 - C#Matías FidemraizerView Answer on Stackoverflow
Solution 3 - C#Pauli ØsterøView Answer on Stackoverflow
Solution 4 - C#AliostadView Answer on Stackoverflow