Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get the type of an interface/class using more than one generic type?

Give the example code below, can anyone explain why the first typeof() call works successfully but the second fails?? It doesn't matter if they are classes or interfaces it fails either way.

interface ITestOne<T1>
{
   T1 MyMethod();
}

interface ITestMany<T1, T2>
{
   T1 MyMethod(T2 myParameter);
}

void Main()
{
    var typeOne = typeof(ITestOne<>); //This line works
    var typeTwo = typeof(ITestMany<>); //Compile error
}
like image 445
Nick Albrecht Avatar asked Feb 21 '13 22:02

Nick Albrecht


People also ask

Can a class implement different instantiations of the same generic interface?

It is prohibited that a type implements or extends two different instantiations of the same interface. This is because the bridge method generation process cannot handle this situation.

Can interface be generic in Java?

Java Generic Interface In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap<String, List<String>>(); is valid.

Can interface be generic in c#?

You can declare variant generic interfaces by using the in and out keywords for generic type parameters. ref , in , and out parameters in C# cannot be variant. Value types also do not support variance. You can declare a generic type parameter covariant by using the out keyword.

Which of the following syntax is used to declare a generic interface?

The general syntax to declare a generic interface is as follows: interface interface-name<T> { void method-name(T t); // public abstract method. } In the above syntax, <T> is called a generic type parameter that specifies any data type used in the interface.


1 Answers

You need to let the compiler know that you're looking for the generic type with two generic arguments. Add a comma between the angle brackets:

var typeTwo = typeof(ITestMany<,>);
like image 56
TheEvilPenguin Avatar answered Oct 22 '22 05:10

TheEvilPenguin