Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Type in constructor

I have a Generic Type Interface and want a constructor of an object to take in the Generic Interface.
Like:

public Constructor(int blah, IGenericType<T> instance)
{}

I want the code that creates this object to specify the IGenericType (use Inversion of Control). I have not seen a way for this to happen. Any suggestions to accomplish this?

I want someone to create the object like:

Constructor varname = new Constructor(1, new GenericType<int>());
like image 715
CSharpAtl Avatar asked Mar 31 '09 13:03

CSharpAtl


People also ask

What is generic type?

A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept.

Can you make a generic constructor?

As we all know that constructors are like methods but without return types. Like methods, constructors also can be generic. Even non-generic class can have generic constructors. Here is an example in which constructor of a non-generic class is defined as generic.

Can generic class have constructor in Java?

Constructors are similar to methods and just like generic methods we can also have generic constructors in Java though the class is non-generic. Since the method does not have return type for generic constructors the type parameter should be placed after the public keyword and before its (class) name.

Can constructor be generic in C#?

No, generic constructors aren't supported in either generic or non-generic classes.


1 Answers

You can't make constructors generic, but you can use a generic static method instead:

public static Constructor CreateInstance<T>(int blah, IGenericType<T> instance)

and then do whatever you need to after the constructor, if required. Another alternative in some cases might be to introduce a non-generic interface which the generic interface extends.

EDIT: As per the comments...

If you want to save the argument into the newly created object, and you want to do so in a strongly typed way, then the type must be generic as well.

At that point the constructor problem goes away, but you may want to keep a static generic method anyway in a non-generic type: so you can take advantage of type inference:

public static class Foo
{
    public static Foo<T> CreateInstance<T>(IGenericType<T> instance)
    {
        return new Foo<T>(instance);
    }
}

public class Foo<T>
{
    public Foo(IGenericType<T> instance)
    {
        // Whatever
    }
}

...

IGenericType<string> x = new GenericType<string>();
Foo<string> noInference = new Foo<string>(x);
Foo<string> withInference = Foo.CreateInstance(x);
like image 158
Jon Skeet Avatar answered Oct 04 '22 08:10

Jon Skeet