tags:

views:

88

answers:

1

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?

+3  A: 

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";
}
Andrew Hare