Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set this static private member of a static class with reflection?

Tags:

c#

reflection

I have a static class with static private readonly member that's set via the class's static constructor. Below is a simplified example.

public static class MyClass {     private static readonly string m_myField;      static MyClass()     {         // logic to determine and set m_myField;     }      public static string MyField     {         get         {             // More logic to validate m_myField and then return it.         }     } } 

Since the above class is a static class, I cannot create an instance of it in order to utilize pass such into a FieldInfo.GetValue() call to retrieve and later set the value of m_myField. Is there a way I'm not aware to either get use the FieldInfo class to get and set the value on a static class or is the only option is to refactor the class I've been asked to unit test for?

like image 288
JamesEggers Avatar asked Feb 24 '10 22:02

JamesEggers


People also ask

Can a static class have private members?

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

How do you set a private static field value in Java?

So: field. set(null, p_fieldValue); This will let you set the static field.

Can we declare a variable private static?

A variable declared private static could easily be accessed, but only from the inside of the class in which it is defined and declared. It is because the variable is declared private, and private variables are not accessible outside the class. Within the class, they can be accessed using ClassName.

What is the difference between private and private static?

A private variable is only accessible inside the class. A static variable belongs to the class rather than to an instance of a class. Notice that the variable DEPARTMENT is also final , which means that it cannot be modified once it is set.


1 Answers

Here is a quick example showing how to do it:

using System; using System.Reflection;  class Example {     static void Main()     {         var field = typeof(Foo).GetField("bar",                              BindingFlags.Static |                              BindingFlags.NonPublic);          // Normally the first argument to "SetValue" is the instance         // of the type but since we are mutating a static field we pass "null"         field.SetValue(null, "baz");     } }  static class Foo {     static readonly String bar = "bar"; } 
like image 108
Andrew Hare Avatar answered Sep 29 '22 09:09

Andrew Hare