The code segment below prints out "The types ARE NOT the same.". Why? I am aware of the fact that using interfaceOnMyType.GetGenericTypeDefinition() will solve the problem, but why should I have to do that?
class Program
{
static void Main(string[] args)
{
var myType = typeof(Baz<>);
var interfaceOnMyType = myType.GetInterfaces().SingleOrDefault();
var exactType = typeof(IBar<>);
if (exactType == interfaceOnMyType)
{
Console.WriteLine("The types ARE the same.");
}
else
{
Console.WriteLine("The types ARE NOT the same.");
}
Console.ReadLine();
}
}
interface IBar<T>
{
}
class Baz<T> : IBar<T>
{
}
interfaceOnMyType.GetGenericTypeDefinition()
returns you the closed constructed type of the interface which is different from the type returned from
typeof(IBar<>)
Here is the MSDN article on GetGenericTypeDefinition, and here is a good quote from it explaining how it works:
Given a
Typeobject representing this constructed type, theGetGenericTypeDefinitionmethod returns the generic type definition.
I think I may have found it now. The reason that the type comparison is failing is because the Type returned from myType.GetInterfaces() is close to but not identical to the type of the interface itself.
According to MSDN:
If you use the
BaseTypeproperty to obtain the base type ofDerived, theFullNameproperty of the resulting Type object returnsnull(Nothing in Visual Basic). To get a non-nullFullName, you can use theGetGenericTypeDefinitionmethod to get the generic type definition.
So I think this is the problem you are seeing. Since base interfaces are retrieved via GetInterfaces any type retrieved by that call will not have a FullName (source). Since it does not have a FullName the types will fail in comparison.
What I orginally wrote would be true if you were comparing the constructed type which you are not. So unfortunately my first answer is dead wrong - I have left it so that the comments left will make sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With