Create a Class in .NET without calling it’s Constructor (and other .NET dark magics)

I stumbled on something kind of useful the other day that I figured I’d share. I was messing around with .NET’s cool Reflection.Emit functionality for dynamically creating classes at runtime but I kept running into a problem: despite my best efforts to add a constructor to my classes dynamically, GetType().GetConstructor() always returned null. The only way I know of to create an object at runtime is to Invoke() the constructor, so the null constructor was obviously problematic. The classes I was creating were really more structlike, there wasn’t any particularly important functionality that I needed to put into the constructor… I just needed a way to new up the object.

That’s when a friend at work pointed me at the FormatterServices class in the System.Runtime.Serialization namespace. It turns out you can call FormatterServices.GetUninitializedObject() and .NET will create the object in memory without invoking the constructor. I have no idea whether or not this is a recommended approach, it definitely seems like a bit of black magic. Doubtless I could have gotten around the issue in the first place by dabbling a bit more in the realm of ConstructorBuilders and IL, but this approach definitely works for what I need and maybe it will save someone else some grief as well.

Leave a Reply