dimanche 2 août 2020

Unexpected behavior when checking equality of property where value is modified in the getter [duplicate]

Given the following class:

public class Employee
{
    private string _birthday { get; set; }
    public string Birthday
    {
        get
        {
            if (DateTime.TryParse(_birthday, out DateTime dateOfBirth))
                return dateOfBirth.AddYears(2000 - dateOfBirth.Year).ToString("MMM dd yyyy");
            else
                return null;
        }
        set
        {
            _birthday = value;
        }
    }
}

And the following code:

static void Main()
{
    var obj1 = new Employee() { Birthday = "Aug 02 2000" };
    var obj2 = new Employee() { Birthday = "Aug 02 2000" };

    var propA = typeof(Employee).GetProperty("Birthday");

    object obj1_propA_object = propA.GetValue(obj1);
    object obj2_propA_object = propA.GetValue(obj2);
    dynamic obj1_propA_dynamic = propA.GetValue(obj1);
    dynamic obj2_propA_dynamic = propA.GetValue(obj2);

    if (obj1.Birthday == obj2.Birthday)
        Console.WriteLine("EQUALS");
    else
        Console.WriteLine("NOT EQUALS");
    // Writes EQUALS

    if (obj1_propA_object == obj2_propA_object)
        Console.WriteLine("EQUALS");
    else
        Console.WriteLine("NOT EQUALS");
    // Writes NOT EQUALS

    if (obj1_propA_dynamic == obj2_propA_dynamic)
        Console.WriteLine("EQUALS");
    else
        Console.WriteLine("NOT EQUALS");
    // Writes EQUALS    
}

I can't understand why the property values when treated as "objects" are not considered equal, but they are seen as equal when comparing them as strings or dynamic. It seems to have something to do with the fact that the values are modified in the getter, since if I change the getter to return just "_birthday" without modifying it the equality comparison as an object works.

I'm happy to use "dynamic" instead of "object", but I would simply like to understand why.





Aucun commentaire:

Enregistrer un commentaire