Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the members of an inherited interface not available using reflection?

Tags:

c#

reflection

When reflecting on an interface type, I only get the members of the specific type, not inherited members.

In this over-simplified example, the program only prints "Name", not "ItemNumber", "Name" as I would expect:

using System;

public interface IBasicItem
{
    string ItemNumber { get; set; }
}

public interface IItem : IBasicItem
{
    string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var type = typeof (IItem);
        foreach (var prop in type.GetProperties())
            Console.WriteLine(prop.Name);
    }
}

What is the rationale behind this ? When I am inheriting from the base interface, I am saying that any of the implementations of my interface, must also implement the inherited members. In other words, IItem is-a IBasicItem. So why does the inherited member not show up using reflection ?

like image 232
driis Avatar asked Dec 02 '22 06:12

driis


1 Answers

I think this is exactly what Phil Haack just blogged about.

From the ECMA-335 Common Language Infrastructure specification:

8.9.11 Interface type derivation Interface types can require the implementation of one or more other interfaces. Any type that implements support for an interface type shall also implement support for any required interfaces specified by that interface. This is different from object type inheritance in two ways:

  • Object types form a single inheritance tree; interface types do not.
  • Object type inheritance specifies how implementations are inherited; required interfaces do not, since interfaces do not define implementation. Required interfaces specify additional contracts that an implementing object type shall support.

To highlight the last difference, consider an interface, IFoo, that has a single method. An interface, IBar, which derives from it, is requiring that any object type that supports IBar also support IFoo. It does not say anything about which methods IBar itself will have.

Referenced from: http://haacked.com/archive/2009/11/10/interface-inheritance-esoterica.aspx

like image 125
blu Avatar answered May 09 '23 03:05

blu