Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetInterface and nested types

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.

  • std has a value of typeof(IStandardInterface)
  • nested has a value of null

Is this behavior expected or a bug? If it is expected could you explain why?

I use .net Framework version 3.5 SP1.

like image 372
Fionn Avatar asked Jul 21 '26 03:07

Fionn


1 Answers

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.

like image 67
JaredPar Avatar answered Jul 23 '26 18:07

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!