MemLeak
MemLeak

Reputation: 4640

How to create an Object from Generics in c#

Im trying to test a few classes with the same methods but different logic, so i want to create a testcase which is generic. how can i instantiate the generic methode?

My Example:

[TestClass]
public class GenericTest<T : MyBuilder>
{
  T target;

  [TestInitialize()]
  public void MyTestInitialize()
  {
      target = new T(param1, param2, param3, param4); // here i'm obviosly stuck
  }

  [TestMethod]
  public void TestMethodBuilder()
  {
      Assert.AreEqual<string>(GetNameAsItShouldBe(),target.BuildName());
  }

  abstract public string GetNameAsItShouldBe();
}

So how can i instantiat the class? I've a strong Java background, so my code is may not c# compatible.

Upvotes: 2

Views: 77

Answers (2)

AlSki
AlSki

Reputation: 6961

You can also specify that the T has a parameterless constructor

public class GenericTest<T : MyBuilder> where T: new()

This will ensure that your T has a default constructor and allow you access to it in your TestInitialize. See http://msdn.microsoft.com/en-us/library/d5x73970.aspx

If however you don't want to specify that then you can define a factory method on your T, i.e.

interface IBuildGenerically<T1, T2, T3, T4>
{
    T Build(T1 param1, T2 param2, T3 param3, T4 param4);
}

public class GenericTest<T : MyBuilder> 
  where T: IBuildGenerically<int, string, int, bool>

Upvotes: 1

Lee
Lee

Reputation: 144136

For a constructor with parameters you have to use reflection:

public class GenericTest<T> where T : MyBuilder
{
    [TestInitialize]
    public void Init()
    {
        target = (T)Activator.CreateInstance(typeof(T), new object[] { param1, param2, param3, param4 });
    }
}

Upvotes: 2

Related Questions