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.
Asked
Active
Viewed 2.1k times
29

Chance
- 11,043
- 8
- 61
- 84
2 Answers
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);
-
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
-
I'm guessing this is against a type for which @Chance does not have source code. – Randolpho Feb 04 '10 at 22:03
-
Yea, I can't muck around with the source & I'm unfortunately blocked into 2.0 w/out extension methods. Thanks though! – Chance Feb 04 '10 at 22:04
-
2Extension methods cannot access private data. http://msdn.microsoft.com/en-us/library/bb383977.aspx – Steve Guidi Feb 04 '10 at 22:46