In a previous article I wrote how to parse Roman Numerals using C#. This article will focus on how to calculate with the class in an intuitive way. It will show how to implement implicit casting and the add and subtraction operator overloads. Fun stuff that’s probably useful in other projects.

It would be great to do stuff like this:

Implement implicit casting

The first thing we’ll need to implement is implicit casting. This will enable the class to interact with strings and integers without having to cast them to a RomanNumeral first. Let’s look at the code:

What are the drawbacks of this method? Well, theĀ Parse might return aĀ null when the string is not parsable (l33t is not a valid Roman Numeral). This might result in a null-reference exception. The constructor method will throw an exception when anything below 0 is passed. This is something you might want to work around.

Plus and minus operator overloading

Now let’s implement the arithmetical operators +, ,Ā /,Ā * andĀ %Ā for theĀ RomanNumeral class. Notice that negative numbers are not supported in this example. We’ll default to 0 (orĀ nulla as the Romans would call it).

Because we’ve implemented implicit conversions first the class handles operation on strings and integers automagically:

Beautiful, I say!

Comparison operators

Mathematical operations are one thing, but how about comparing Roman Numerals? Implementing anĀ IComparable andĀ IComparable<RomanNumeral> will allow sorting mechanisms to handle the class.

Notice how I’m not using theĀ == or the != operators. This will prevent infinite loops when we implement these operators using the compare methods. TheĀ object.ReferenceEquals will do the job.

Implementing the operator overloads

Now let’s implement theĀ ==,Ā !=,Ā <,Ā <=,Ā >,Ā >= operators using theĀ statisĀ Compare method.

Implement equals

The equality method can also be implemented using the CompareTo method. Remember that theĀ GetHashCode should be overridden as well.

Summary

Iā€™ve shown how one can do arithmetic using Roman Numerals. Implicit casting and operator overloading are very helpful in this case. You canĀ download the class from GitHubĀ and use it in your projects.