Creating an Instance Without Using Constructors

I recently worked on a complicated API project which had tight coupling. To create an instance of my class, I had to instantiate two variables of other classes, which were themselves difficult to instantiate (one didn’t have a public constructor).

As a simplified example, I need to instantiate A, which only has one constructor:

public class A(B b, C c);

In this case, C did not have public constructors, and B required instances of other classes which were not trivial to instantiate.

Sigh.

Reflection to the rescue! Actually, no. Using the usual someType.GetConstuctor(...).Invoke(null) required a parameterless constructor; ditto for Activator.CreateInstance. While I could have simply added a parameterless constructor, since this project was an API, that would change the API and possibly cause other problems if used outside of testing.

While searching for another solution, I found this pro tip by Mark Gravell: you can actually create an instance without initializing it by calling:

A a = (A) System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof(A));

Where A is the class you wish to instantiate. It’s tricky, and probably not what you ever want to do in production code; in test code, it was exactly the solution I needed. Thanks, Mark!

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Web, Wndows Forms and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *