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

Chance picture Chance · Feb 4, 2010 · Viewed 17.9k times · Source

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.

Answer

JaredPar picture JaredPar · Feb 4, 2010

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