29

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.

Chance
  • 10,647
  • 6
  • 56
  • 77

2 Answers2

55

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);
Tom
  • 5,877
  • 4
  • 27
  • 45
JaredPar
  • 703,665
  • 143
  • 1,211
  • 1,438
  • 1
    +1 fascinating : what I find a little scary in this technique is : if the field in question is readonly : this code will not cause a run-time error when executed. – BillW Feb 05 '10 at 00:28
  • If the field in question is read-only, does it just do nothing? Or does it set the value anyway? Is this just .NET 3.5? – J.Hendrix Feb 05 '10 at 20:57
  • 6
    +1. I think for private static you need some BindingFlags as the second parameter of the GetField method. BindingFlags.Static | BindingFlags.NonPublic – user420667 Mar 06 '14 at 22:20
1

could you create a static function that is public and use it to set your private static variable ?

John Boker
  • 80,803
  • 17
  • 95
  • 130