user2390678
user2390678

Reputation: 33

Strange behaviour with properties

I have a strange behaviour with C#.

I've got a class that includes statics, something that lokks like that :

 public class Status
 {
     public int Id { get; internal set; }
     public string Name { get; internal set;}

     public static Status Created = new TicketStatus { Id = 1, Name = "Created" };
 }

I use it like that (assuming myObj.Status is a Status instance with Id=1 and Name="Created") :

Assert.AreEqual(myObj.Status, Status.Created);
    // True

It works fine, both object are equals.

But if I change my Status class into this :

 public class Status
 {
     public int Id { get; internal set; }
     public string Name { get; internal set;}

     public static Status Created
     {
        get { return new TicketStatus { Id = 1, Name = "Created" }; }
     }
 }

Then the statement

Assert.AreEqual(myObj.Status, Status.Created);
    // False

Does not work anymore, both objects are different.

I don't understand why ?

Upvotes: 3

Views: 102

Answers (1)

Konstantin Chernov
Konstantin Chernov

Reputation: 1936

It's simple - you are comparing references (memory addresses), not object properties. You need to override equality operations within your class. Equals method and GetHashCode also.

Upvotes: 7

Related Questions