How to compare two objects (testing for equality) in C#

Hacktoberfest and the promise of free t-shirts had me looking for a project to help with this month. That’s how I stumbled across GeneGenie.Gedcom, a genealogical library written in C# (read more about it here), and found myself reviewing everything I know about class equality. I focused on implementing some logic to make sure changes were correctly detected, and in order to do that I had to define “equality” for each class that represented some facet of genealogical research. Why was that? Let’s take two instances of a class – one with data that’s fresh from the »

The effect of the Obsolete attribute on a class is ignored when there's an interface involved

While marking some code obsolete the other day, I noticed an unexpected behavior (at first glance). Say you have a class, and an interface it implements. The second argument (true) indicates whether or not you’re allowed to call the method, and it means the difference between a simple warning and an error preventing compilation. public interface ISampleClass { void SomeOldMethod(); } public class SampleClass : ISampleClass { [Obsolete("This is the old way. No one uses it anymore. Shame on you!!", true)] public void SomeOldMethod() { // This is old. I should probably remove and refactor, but I'm too scared. Console.WriteLine("Oooooooooooooollllllllllld stuff."); Console. »

Mocking Dependencies (silly dependency! um... not that kind of mocking)

The code in this post is also available on Github. In a mood at work the other day (after hunting down some obscure bug that would’ve been more apparent, had I had some relevant failing tests to point me in the right direction), I started back-filling old code with unit tests. That meant removing some dependencies on things I didn’t actually need to test, so I’ll post a few (contrived) examples. Don’t Rely on External Dependencies One of the most critical pieces of unit testing (although not overly complicated, as I’ll show) is mocking out »

Relative Ordering with IComparable and CompareTo

Someone asked a question on StackOverflow about the difference between the int CompareTo method and an ordinary If condition. As it turns out, the poster’s if statement is exactly how Int32 implements CompareTo. The IComparable and IComparable<T> interfaces each have only a single method, which can be used to compare two objects for the purpose of determining how they should be ordered relative to one another. // IComparable<T> - Compares the current object with another object of the same type. int CompareTo(T other); // IComparable - Compares the current object with another object. int »