Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Reflection to set a static variable value before object's initialization?

Is there anyway to set the value of a static (private) variable on an object that has not been initialized? The SetValue method requires an instance, but I'm hoping there's a way to get around this.

like image 304
Chance Avatar asked Feb 04 '10 21:02

Chance


People also ask

Can you change the value for a static variable Once initialized?

Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods. However, non-static methods have access to all variables (instance or static) and methods (static or non-static) in the class.

Can a class have static constructor?

A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.


1 Answers

For static values you can pass null for the instance parameter.

var type = typeof(SomeClass); var field = type.GetField("SomeField", BindingFlags.NonPublic | BindingFlags.Static); field.SetValue(null, 42); 
like image 171
JaredPar Avatar answered Oct 06 '22 19:10

JaredPar