Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Type with multiple generic type parameters

Tags:

c#

generics

I have been searching of a while now, and have still not been able to find an answer to my question, instead I find answers to Making a Generic Method with multiple Generic Type parameters.

So, this is my problem. I have an interface IMyInterface<T1, T2>and I want to create it as a Type. Currently I can create the type for IMyInterface<T> like this :

Type type = typeof(IMyInterface<>).MakeGenericType(genericTypeForMyInterface) 

Any assistance would be greatly appreciated.

Thanks :)

like image 493
Arran549 Avatar asked Mar 05 '15 10:03

Arran549


People also ask

Can a generic class have multiple generic parameters?

A Generic class can have muliple type parameters.

How do you add two generic values in Java?

You have to add the numbers as the same type, so you could do x. intValue() + y. intValue(); .

How many type parameters can be used in a generic class?

Multiple parameters You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.

Can you create instances of generic type parameters?

You cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.


1 Answers

MakeGenericType takes params Type[] as arguments which will be used to construct a generic type. Which means that you could pass any number of arguments.

So you could simply do

Type type = typeof(IMyInterface<,>).MakeGenericType(type1, type2);

Note you need a comma (,) in between the angular brackets for types with multiple generic type parameters. You need n-1 comma(s) for (n) type parameters. i.e one comma for two type parameter, two commas for three type parameters an so on.

like image 118
Sriram Sakthivel Avatar answered Nov 09 '22 06:11

Sriram Sakthivel