I have code that compares 2 PropertyInfos with Equals (). Although this usually works, I came across a strange situation when two objects of information about objects with reflection for the same basic property are not equal:
PropertyInfo prop1, prop2; // both are public and not static Console.WriteLine(prop1 == prop2); // false ??? Console.WriteLine(Equals(prop1, prop2)); // false ??? Console.WriteLine(prop1.DeclaringType == prop2.DeclaringType); // true Console.WriteLine(prop1.ReturnType == prop2.ReturnType); // true Console.WriteLine(prop1.Name == prop2.Name); // true Console.WriteLine(prop1.DeclaringType.GetProperties().Contains(prop1)); // true Console.WriteLine(prop2.DeclaringType.GetProperties().Contains(prop2)); // false ???
It seems that PropertyInfo does not actually implement Equals (), but I thought .NET caches the reflected elements, so the same instance always returns. You will definitely see a.GetType () == b.GetType () all the time. Does this apply to PropertyInfos?
Some other notes: -This oddity occurred when running the NUnit test in .NET 4, VS2012, x86 build target -This does not happen even with all the properties that we compare in this way, but fail in sequence on the same property.
Can anyone explain this behavior?
EDIT: in case anyone is interested, here is the EqualityComparison function that I wrote to compare MemberInfos:
public class MemberEqualityComparer : EqualityComparer<MemberInfo> { public override bool Equals(MemberInfo @this, MemberInfo that) { if (@this == that) { return true; } if (@this == null || that == null) { return false; }
ChaseMedallion
source share