Keep it Simple

// practice, the distance between dream and achievement

Tag: Interface (page 1 of 2)

Check the list of custom class objects contains an object

List<T>.Contains determines equality by using the default equality comparer(System.IEquatable) which uses Object.Equals and Object.GetHashCode methods. In other words, your Custom class should either implement the System.IEquatable (not the System.IEqualityComparer!) interface or override the Object.Equals and Object.GetHashCode methods to support contains method.

Now, you must understand the below methods of System.IEquatable as those needs to be implemented in your custom class

  • GetHashCode
  • Equals

Continue reading

Event – want event to run only once using add/remove properties.

It is a common scenario where you may want to ensure that object is subscribed to an event only once, this can be done easily as shown below

Continue reading

IComparable vs IComparer in C#

In .NET some of the collection types such as Array, ArrayList, List<T> expose the Sort method that allows you to sort the collection. In order for those classes to sort the collection, there has to be a way for them to somehow compare objects with each other. The most basic Sort method usually does not require any arguments other than the collection itself in case of the static Array.Sort. In this case how does the framework know how to compare our objects? Is person1 greater than person2? Or maybe they are equal? This why we have IComparable & IComparer.

  • IComparable as I’m comparable. which means I can be compared to another instance of the same type.
  • IComparer as I’m a comparer, I simply compare which means I compare two instances.

Continue reading

INotifyPropertyChanged – you know the change.

In some situations, it is not possible for the application to  to realize that the value of a property is changed however you may want to update one or other control in case of a change. 

Fixing this is really simple, if an object implements the INotifyPropertyChanged interface, it’ll raise a property changed event when its property changes.

Continue reading

Older posts

© 2017 Keep it Simple

Theme by Anders NorenUp ↑