Well, it does not have to be always complaints and story-telling. I think there is room also for instructive content and weird post titles.
I am somehow ashamed to admit that although I have been working a lot with the .Net Framework (early 1.0 betas and youth, where are you?) I am still somewhat confused with some basic stuff. It may have to be related to the fact I do not own any certification on the subject (not that having one implies you know about the subject) but my best guess is that it must be a topic to study for a certification exam.
While I was coding a helper class to better encapsulate the concept of "age" and, at the same time, doing some Linq work, it struck me: "Wow, there are quite a few ways to compare objects... Where and when do I use each?". Besides, there are some general rules and a canonical way of implementing value-equality in .Net (and thanks to R# code completion, a very easy one), but I could not find one canonical way for implementing comparison, so I wanted to come up with one myself.
It may sound basic stuff, but I have the bad habit of wanting to learn what I do not know (be it basic or not). It turned out not to be so difficult to guess when to use which, but still there are some places where it seems unclear to me. And also it may be the case that there are others out there with my same lack of knowledge, so this may help them.
I wanted to put my attention on:
- the Equals(obj) method and IEquatable<T> interface
- IComparable and IComparable<T>
- IComparer, IComparer<T> and Comparison<T>
- IEqualityComparer and IEqualityComparer<T>
- equality (== and !=) and comparison (<, <=, >, >=) operators
- Comparer<T> and EqualityComparer<T>
Did I mention that there a a few ways to compare instances?
What I will do is start a series of post in which I will try to unveil the mysteries, oddities and obviousness I found while learning on the subject.
And since I am a code monkey, every part will be accompanied by the code I wrote implementing the plethora of interfaces on a custom Value Type and on a custom Reference Type. I will also start using
Google Code Github to host complete examples that can be downloaded by the reader, should he/she wants to.
Where do I start? Object equality sounds like a good place to me. Sooooo, a small journey starts....