Why doesn't Type.GetProperty(string)
get a property from a base interface if the type is an interface? For example, the following code prints:
System.String X
null
System.String X
System.String X
which seems inconsistent:
void Main()
{
Console.WriteLine(typeof(I1).GetProperty("X"));
Console.WriteLine(typeof(I2).GetProperty("X"));
Console.WriteLine(typeof(C1).GetProperty("X"));
Console.WriteLine(typeof(C2).GetProperty("X"));;
}
public interface I1 { string X { get; } }
public interface I2 : I1 { }
public class C1 { public string X { get { return "x"; } } }
public class C2 : C1 { }
EDIT: another aspect of the runtime that supports Cole's answer is the following:
public class C : I2 {
// not allowed: the error is
// 'I2.X' in explicit interface declaration is not a member of interface
string I2.X { get; set; }
// allowed
string I1.X { get; set; }
}
Remember that class inheritance is not the same as interface implementation.
A derived class and its base class have an is-a relationship. If D : B
then D
is a B
. If B
has a property, then D
will by definition also have that same property, because that's what that relationship means; the "substance" of D
is in some sense altered by its relationship to B
.
Interfaces provide no implementation, so when you say ID : IB
, you're not really saying ID
is a IB
in the same way that you do with classes. What would that even mean? ID
and IB
aren't things; they're agreements. There's nothing there to alter. Instead, you're saying "a class which implements ID
must also provide an implementation for IB
."
The fact that ID
derives from IB
doesn't change ID
because it has no substance to change. It just means that any class which promises to fulfill the contract specified by ID
must also be prepared to adhere to an additional set of requirements.
Bearing this in mind, if IB
provides a property X
, the proper answer to "does ID
have a property X
?" is no. ID
requires you to also implement IB
, which does have a property X
, but it does not itself have a property X
.
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