views:

428

answers:

2

Is there anyway to set a value of a static (private) variable without needing to initalize the object?

The SetValue method requires an instance, but I'm hoping there's a way to get around this.

Thanks!

+7  A: 

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

var type = typeof(SomeClass);
var field = type.GetField("SomeField");
field.SetValue(null, 42);
JaredPar
Sweet, thanks! I really appreciate it.
Chance
+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
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
+1  A: 

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

John Boker
I'm guessing this is against a type for which @Chance does not have source code.
Randolpho
extension method ?
John Boker
Chance
Extension methods cannot access private data. http://msdn.microsoft.com/en-us/library/bb383977.aspx
Steve Guidi