I met strange generic behavior. Below is the code I'm using for testing.
public static class Program { public static void Main() { Type listClassType = typeof(List<int>).GetGenericTypeDefinition(); Type listInterfaceType = listClassType.GetInterfaces()[0]; Console.WriteLine(listClassType.GetGenericArguments()[0].DeclaringType); Console.WriteLine(listInterfaceType.GetGenericArguments()[0].DeclaringType); } }
Output:
System.Collections.Generic.List`1[T] System.Collections.Generic.List`1[T]
It was very strange to me that the second call to Console.WriteLine displays the class, not the interface, because I use a generic type definition. Is this the right behavior?
I am trying to implement generic type inference in my compiler. Suppose I have the code below.
public static class GenericClass { public static void GenericMethod<TMethodParam>(IList<TMethodParam> list) { } }
And I want to call this method as follows:
GenericClass.GenericMethod(new List<int>());
To check the possibility of output, I need to compare the type in the method signature and the type of the arguments passed. But the code below returns false.
typeof(GenericClass).GetMethods()[0].GetParameters()[0].ParameterType == listInterfaceType;
Should I always use Type.GetGenericTypeDefinition for such comparisons?
source share