class MyClass<T> where T: new()
{
public Test()
{
var t = new T();
var t = new T("blah"); // <- How to do this?
}
}
I know that’s not possible as written, and as far as I understand it’s just simply not allowed (although I would love nothing more than to be wrong about that). The first solution that comes to mind is to use an object initializer, but let’s suppose that’s a last resort because it would conflict with other oop goals in this case.
My next inclination would be to use reflection, but before I do that I’d like to know if I am overlooking any easier way to do this or perhaps a different design pattern that would work better?
You can’t do it directly. You’ll need to use
Activator.CreateInstance, but doing so has all the drawbacks of reflection, meaning that you miss out on compile-time checking etc.