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
  • 11,043
  • 8
  • 61
  • 84

2 Answers2

58

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
  • 6,325
  • 4
  • 31
  • 55
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 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
  • 82,559
  • 17
  • 97
  • 130