Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one get the type of a generic class with multiple type parameters? - C#

Tags:

c#

generics

This compiles:

public class A<T> {
    public void test() {
        var a = typeof (A<>);
    }
}

This does not:

public class A<T,S> {
    public void test() {
        var a = typeof (A<>);
    }
}

I get the error: Using the generic type 'A' requires 2 type arguments

How do I get a reference to the type of this generic type with two arguments?

like image 219
oillio Avatar asked Oct 19 '10 02:10

oillio


People also ask

Can a generic class have multiple generic parameters?

A Generic class can have muliple type parameters.

How do you find the type of generic class?

You can get around the superfluous reference by providing a generic static factory method. Something like public static <T> GenericClass<T> of(Class<T> type) {...} and then call it as such: GenericClass<String> var = GenericClass. of(String. class) .

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

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.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.


1 Answers

All you need is a comma:

var a = typeof (A<,>);

Note of course that this will return a System.Type that represents the unbound generic type A. Since the code is in a method that belongs to the type, you might just be looking for typeof (A<T, S>), depending on your requirements.

like image 147
Ani Avatar answered Oct 06 '22 20:10

Ani