mercredi 17 juillet 2019

== operator when comparing object properties using reflection

Strange behavior when comparing two string properties with the usage of reflection.

var a = new A
{
    X = "aa",
    B = 1
};

var b = new A
{
    X = "aa",
    B = 2
};

Type type = typeof(A);

object aObjValue = type.GetProperty("X")?.GetValue(a);
object bObjValue = type.GetProperty("X")?.GetValue(b);

Console.WriteLine("aObjValue == bObjValue : " + (aObjValue == bObjValue));
Console.WriteLine("aObjValue.Equals(bObjValue) : " + aObjValue.Equals(bObjValue));

a.X = Console.ReadLine();

aObjValue = type.GetProperty("X")?.GetValue(a);

Console.WriteLine("aObjValue == bObjValue : " + (aObjValue == bObjValue));
Console.WriteLine("aObjValue.Equals(bObjValue) : " + aObjValue.Equals(bObjValue));

a.X = "aa";

aObjValue = type.GetProperty("X")?.GetValue(a);

Console.WriteLine("aObjValue == bObjValue : " + (aObjValue == bObjValue));
Console.WriteLine("aObjValue.Equals(bObjValue) : " + aObjValue.Equals(bObjValue));

Console.ReadKey();

//aObjValue == bObjValue : True
//aObjValue.Equals(bObjValue) : True
//aa
//aObjValue == bObjValue : False
//aObjValue.Equals(bObjValue) : True
//aObjValue == bObjValue : True
//aObjValue.Equals(bObjValue) : True

When using Console.ReadLine() and manually assigning a.X to "aa" I'm getting false but when assigning it in code again I get true. This is unexpected behavior for me. Can someone explain me what is going on here?





Aucun commentaire:

Enregistrer un commentaire