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?
Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters. Cannot Use Casts or instanceof With Parameterized Types.
To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.
The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section. The type parameter section of a generic class can have one or more type parameters separated by commas.
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.
public Test()
{
var t = (T)Activator.CreateInstance(typeof(T), (object)"blah");
}
You can force user to give you the way to construct the object from string
, like this:
internal class MyClass<T>
where T : new()
{
public void Test(Func<string, T> func)
{
var t = func("blah");
}
}
Function
can be part of contruction MyClass
object, so you won't have to pass it each time you call methods that have to create T
. Actually with that aproach new()
might not be needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With