woensdag 15 december 2010

C# - create an instance of any non-static class

For testing purposes you may want to create an instance of a type that does not have any public constructors, or an instance of a type that only has complex constructors requiring parameters you'd rather not pollute your test with. If, additionally, you're also not concerned about initialization of the instance (or you're content with taking care of it next) here's a trick that may save you some odd hours trying to get all the parameters for that complex constructor or produce some complex bit of Reflection to call that private constructor. You may want to try the FormatterServices.GetUninitializedObject function:

using System.Runtime.Serialization;
/// <summary>
/// Gets an uninitialized instance of type T
/// </summary>
/// <typeparam name="T">Type of object to create an uninitialized instance from</typeparam>
/// <returns>Uninitialized instance of type T</returns>
/// <remarks>BEWARE: no constructors are called when creating the instance of type T, it will be uninitialized and invalid</remarks>
public static T GetUninitializedObject<T>() where T : class
{
    return FormatterServices.GetUninitializedObject(typeof(T)) as T;
}

Geen opmerkingen:

Een reactie posten