vendredi 24 décembre 2021

Reflection considers properties to have different values despite them appearing equal

I have 2 types:

public class TypeA
{
    public int SomeProperty { get; set; }
}
public class TypeB
{
    public int SomeProperty { get; set; }
}

If I create an instance of both types, and in both cases give 'SomePropety' a value of 3, I can retrieve the values of these properties with reflection:

var aProperty = a.GetType().GetProperties().Single(p => p.Name == "SomeProperty");
var bProperty = b.GetType().GetProperties().Single(p => p.Name == "SomeProperty");

var aValue = aProperty.GetValue(a);
var bValue = bProperty.GetValue(b);

Here aValue and bValue now have the value of 3.

But I'm finding that when I compare these raw values, C# does not consider them equal:

if (aValue != bValue)
{
    //this code is hit
}

I look in the debugger and both are clearly '3'. I've never actually encountered this before, have I walked into some scenario where C# considers them unequal because they came from different properties even though they're a raw data type?





Aucun commentaire:

Enregistrer un commentaire