Enhancing the TypeSafe Enum Pattern

By: Brian Dobberteen

As I mentioned in my last post about the Typesafe Enum Pattern in C#/VB.NET, I left out a few features that I had originally wanted to include in that post.

Namely, these features were nothing more than implementing the IComparable<T> and IEquatable<T> interfaces.

Upon further investigation, I’ve found that there is no need to implement IEquatable<T> here, as we’ll see in an example in just a moment.

Also, I’m not sure how often we’d find ourselves needing to sort collections of our enum-esque class.

Here’s the original class from the previous post:

The ‘Enum’ Class

This will be our baseline to begin implementing the interface(s):

Again, if you’d like to re-familiarize yourself with the above code and its features, check out the original post: Typesafe Enum Pattern in C#/VB.NET.

Do We Need IEquatable<T>?

See for yourself:

This behaves just as a normal Enum would. Clearly, there is no need to implement IEquatable<T> in this case.

Do We Need IComparable<T>

IComparable<T>, on the other hand, might prove useful if we ever find ourselves wanting to sort an Array, etc, of UselessItem pseudo-Enums.

Without implementing IComparable<T>, we are not able to do:

Implementing IComparable<T>

IComparable<T> is definitely one of the easier interfaces to implement – it only requires the implementation of a single method:

int CompareTo(T other);

CompareTo returns:

If this object is less than the other argument, the method returns a negative integer.If this object is equal to the other argument, the method returns zero.

If this object is greater than the other argument, the method returns a positive integer.

See MSDN’s Entry on IComparable<T> for more information.

This mechanism is what allows, for example, Array.Sort() to work easily with a simple lambda expression.

So let’s implement it!

In line 18, you can see that we want to be able to sort by our ItemName property. Sorting the GUID ItemIDs is probably something of little interest, but it certainly can be done as well. In fact, this pattern can be used to make our enum-esque Class sortable by whatever property/datatype we might need for our purposes.

Let’s try a sample sort:

Not too shabby!


Well, we haven’t added a ton of real-world useful functionality to our enum-esque Class, though it was an easy way to demonstrate the implementation and usefulness of IComparable<T>. Initially, I had thought that implementing IEquatable<T> was also necessary to do simple operations such as:

But, as it turns out, the nature of our enum-esque class gives us the above capability out-of-the-box.

And free stuff, that works as expected? A rarity these days!

Leave a Reply

Your email address will not be published. Required fields are marked *