C#C
C#16mo ago
CyberBotX

Is it possible to use Reflection to replace a static readonly field without the static constructor?

So, say for example I have a class like the following:
class Test
{
    static readonly string Value = throw new NotImplementedException();
}

Obviously, trying to use that class will result in a TypeInitializationException being thrown. I had thought to use Reflection to do something like this:
typeof(Test).GetField("Value", BindingFlags.NonPublic | BindingFlags.Static)!.SetValue(null, "TestValue");

(The exception is thrown when SetValue is called, not when GetField is called.)

But this results in the type being initialized and thus the same exception is thrown. I know that trying to do something like this is probably frowned upon, but I am trying to get around an issue in an externally generated class that I'd rather not modify (despite that I could in this case) just in case I have to re-generate the file again. So is there any way around this to be able to replace the value of that static readonly field without the static constructor being called and thus throw an exception?
Was this page helpful?