© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
30 replies
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();
}
class Test
{
    static readonly string Value = throw new NotImplementedException();
}

Obviously, trying to use that class will result in a
TypeInitializationException
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");
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ It it possible to get name of attribute without reflection?
C#CC# / help
3y ago
Cannot set readonly field in inherited constructor [Answered]
C#CC# / help
4y ago
Is it possible to pin an array using reflection?
C#CC# / help
2y ago