Let's say I have the following classes:
public class Class1<T>
where T : SubClass1, new()
{
public T Item { get; protected set; }
public Class1()
{
Item = new T();
}
}
public class Class2<T> : Class1<T>
where T : SubClass1, new()
{
public Class2()
{
Item = new T();
}
}
public class SubClass1
{
public string Text { get; protected set; }
public SubClass1()
{
Text = "SubClass1";
}
}
public class SubClass2 : SubClass1
{
public SubClass2()
{
Text = "SubClass2";
}
}
Now I want a generic method to create those classes, so I make this:
public T GetInstance<T, K>()
where T : Class1<K>, new()
where K : SubClass1, new()
{
return new T();
}
But if I call that method, I have to do this:
GetInstance<Class2<SubClass1>, SubClass1>();
So I'm specifying SubClass1
twice to call the method. My question is, is there a neater way of doing this which would be more like this:
GetInstance<Class2<SubClass1>>();
And therefore avoid specifying SubClass1
twice? Am I missing something?