views:

60

answers:

1

Is there any shorthand for using an extension method to instantiate and initialise an object?

My aim is to abstract-away and encapsulate the code required to instantiate and initialise an instance of MyType suitable for unit testing.

Example:

//...
//convoluted client code - I'd like to avoid the null instance creation
MyType t = null;
t = t.GetTestInstance();
//...

//extension method
public static class MyTypeExtensions
{
  public static MyType GetTestInstance(this MyType t)
  {
    var ctorInjectedDependency = blah;

    return new MyType(ctorInjectedDependency);
  }
}
+1  A: 

Maybe something like this will suit your needs:

public class MyType
{
  public MyType(string s)
  {
    Property = s;
  }

  public string Property { get; set; }
}

public static class MyTypeExtensions
{
  public static object GetTestInstance(this Type t)
  {
    var ctorInjectedDependency = "blah";
    var ctorInfo = t.GetConstructor(new[]{typeof(string)});

    return ctorInfo.Invoke(new object[] {ctorInjectedDependency});
  }

  public static T GetTestInstance<T>(this Type t)
  {
    var ctorInjectedDependency = "blah";
    var ctorInfo = t.GetConstructor(new[] { typeof(string) });

    return (T)ctorInfo.Invoke(new object[] { ctorInjectedDependency });
  }
}

Usage:

var my = typeof(MyType).GetTestInstance(); // maybe just object is enough
var my2 = typeof(MyType).GetTestInstance<MyType>();


Console.WriteLine((my as MyType).Property);
Console.WriteLine(my2.Property);
Bazurbat