4

why typeof(t).GetProperties() does not find all the public properties of t when t is a derived interface? Is this the expected behavior or I am missing something?

public interface IBaseOne
    {        int Id { get; }    }

public interface IDerivedOne : IBaseOne
    {        string Name { get; }    }

public class ImplementsIDerivedOne : IDerivedOne
    {
        public int Id { get; private set; }
        public string Name { get; private set; }
    }

public static class TypeOfTests
    {
        public static Type Testing<T>() where T : class,IBaseOne
        {
            return typeof(T);
        }
    }

class Program
{
    static void Main(string[] args)
    {
        Type typeFromIBaseOne = TypeOfTests.Testing<IBaseOne  >() ;
        Type typeFromIDerivedOne = TypeOfTests.Testing<IDerivedOne>();
        Type typeFromImplementsIDerivedOne = TypeOfTests.Testing<ImplementsIDerivedOne>();

        PropertyInfo[] propsFromIBaseOne = typeFromIBaseOne.GetProperties();
        PropertyInfo[] propsFromIDerivedOne = typeFromIDerivedOne.GetProperties();
        PropertyInfo[] propsFromImplementsIDerivedOne =TypeFromImplementsIDerivedOne.GetProperties();

        Debug.Print("From IBaseOne: {0} properties", propsFromIBaseOne.Length);
        Debug.Print("From IDerivedOne: {0} properties", propsFromIDerivedOne.Length);
        Debug.Print("From ImplementsIDerivedOne: {0} properties", propsFromImplementsIDerivedOne .Length );
    }
}

Result: From IBaseOne: 1 properties From IDerivedOne: 1 properties From ImplementsIDerivedOne: 2 properties

Why IDerivedOne only shows 1 property?

thank you

Enrique

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

1 Answers1

5

That's because interfaces do not "derive" from one another; think of them as contracts that implementing classes must honor. Therefore, when you have this:

interface IFoo : IBar { }

it does not mean that IFoo itself has the same members that IBar does. It means that any implementers of IFoo also take on the responsibility of implementing IBar. The distinction might sound like fine print when viewed from the implementer's perspective, but it does make a very important difference to the type system.

If you want specifically to find out which properties must be defined by an implementor of IDerivedOne instead of which properties IDerivedOne declares you will have to reflect on IDerivedOne, find its "base" interfaces and recursively enumerate their members.

Jon
  • 428,835
  • 81
  • 738
  • 806