Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating a generic type with an overloaded constructor

Tags:

c#

oop

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?

like image 970
Brandon Moore Avatar asked Feb 03 '12 11:02

Brandon Moore


People also ask

Can you instantiate a generic type?

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.

How do you declare a generic type in Java?

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.

How do you declare a generic type in a class explain?

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.


2 Answers

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");
}
like image 74
LukeH Avatar answered Sep 19 '22 02:09

LukeH


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.

like image 39
Piotr Auguscik Avatar answered Sep 21 '22 02:09

Piotr Auguscik