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.
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));
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!