I just discovered a very strange behavior with Type.GetInterface and nested Types.
The following sample code will show the problem, I am using the Type.FullName of an interface to check whether a given type derives from that interface:
public interface IStandardInterface {}
public class StandardClass : IStandardInterface {}
class Program
{
public interface INestedInterface {}
public class NestedClass : INestedInterface { }
static void Main()
{
var stdIfName = typeof (IStandardInterface).FullName;
var nestedIfName = typeof (INestedInterface).FullName;
var std = typeof(StandardClass).GetInterface(stdIfName);
var nested = typeof(NestedClass).GetInterface(nestedIfName);
}
}
If I execute the code above it works for StandardClass but not for NestedClass.
Is this behavior expected or a bug? If it is expected could you explain why?
I use .net Framework version 3.5 SP1.
Expanding on Marc's answer.
Although it's not documented, the GetInterface API will break up the name you pass in based on the position of the last "." in the name. Everything to the right of the "." will be assumed to be the short name of the interface in question.
This poses a problem for nested types as they will have a name which is "ContainingTypeName+NestedTypeName". So when you pass in the full name to GetInterface it actually ends up looking for an interface named "Program+INestedInterface" which it won't find.
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