Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of a public static field via reflection

Tags:

c#

.net

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";    } } 
like image 234
Omu Avatar asked May 05 '11 13:05

Omu


People also ask

How do you call a static variable from another class?

Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

Should static fields be public?

Public static fields are useful when you want a field to exist only once per class, not on every class instance you create. This is useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.

What is static field in Java?

Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory.


2 Answers

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

fields[0].GetValue(null) 
like image 185
Thomas Levesque Avatar answered Sep 28 '22 23:09

Thomas Levesque


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); 
like image 43
Matías Fidemraizer Avatar answered Sep 28 '22 21:09

Matías Fidemraizer