Again, about my Twitter Client. I’ve made a custom class show the tweet and then a ICollection for the public property of the Tweets in the TwitterViewModel.

Problem: Each I time I get new tweets I have to empty the Collection. I tried to use the Contains method every time I added a new Tweet, but as Pete Brown said that will always return false.

Solution: Implement IEquatable<Tweet> on my Tweet class. Now when Contains check if the tweet exists in the list it will work.

Other example.

Say you have this custom class:

class User
      public string Name { get; set; }
      public long ID { get; set; }

Not going to bother INotifyPropertyChanged. This will be only about the IEquatable class.

Create a ICollection<User> and add some data:

ICollection<User> list = new List<User>();
list.Add(new User { Name = “Robert”, ID = 123409 });
list.Add(new User { Name = “Pete”, ID = 23410 });

Now. Say you have some form that creates a new User, check if it exists and then tries to add it. For sake of simplicity I won’t use a form:

var user = new User { Name = “Pete”, ID= 23410 });

This won’t work. It’ll add it even you know that it contains it. Simply put “Two instances of a class representing the same tweet (or in this case user) are two different things.” (@Pete_Brown on Twitter)

Implement the IEquatable class and your class should look like this:

class User: IEquatable<User>
      public string Name { get; set; }
      public long ID { get; set; }

      public bool Equals(User other)
            if(other.ID == this.ID)
                  return true;
                  return false;

Now Contains() will work properly and your List manipulations will work like a charm.

Hope you found this post useful. It’s been a pain of figuring it out. Had help from Pete Brown.
Subscribe to his blog:
Follow him on Twitter:

Me? You can find my blog at (mouthful I know) and Twitter:

Stay tuned for more interesting finds…