Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a member of base class different from the same member in derived class?

This is a followup to this question: Lambda expression not returning expected MemberInfo

class Human
{
    public string name { get; set; }
}

class Man : Human
{

}

var m1 = typeof(Human).GetProperty("name");
var m2 = typeof(Man).GetProperty("name");

//m1 != m2 why?

The same holds for MethodInfos.

I can understand there has to be a difference when Human is an interface, or when name of Human is abstract/virtual. But why is it so for sealed types? Isn't name of Man exactly name of Human?

Clarification: As Jon says their ReflectedTypes are different. ReflectedType in equality should come handy when deciding equality of interface members or overridden members since they are different. But I don't think it should be considered for deciding equality of simple cases like above. May be the design team wanted to be consistent. Just wondering what rationale drove framework designers to consider ReflectedType property in deciding equality of same member spanning over multiple classes.

like image 881
nawfal Avatar asked Mar 25 '23 03:03

nawfal


1 Answers

They differ in their ReflectedType property:

The ReflectedType property retrieves the Type object that was used to obtain this instance of MemberInfo. This may differ from the value of the DeclaringType property if this MemberInfo object represents a member that is inherited from a base class.

So if you print out m1.ReflectedType, it should print Human. If you print out m2.ReflectedType, it should print Man.

EDIT: In terms of why the equality operator is implemented this way: it's always a delicate design decision to work out what == should mean, in the case where there may be distinguishable but not "primary" differences between objects. This is where providing different IEqualityComparer implementations is useful, but of course that doesn't work for the operators themselves.

In general, if x == y is true then it's quite unusual for x.Foo to be different to y.Foo for any property. I can't immediately think of any cases where that occurs in the framework.

like image 122
Jon Skeet Avatar answered Apr 09 '23 21:04

Jon Skeet