Make extension methods that convert to and from Roman numerals in C#

The example Convert to and from Roman numerals in C# uses the RomanToArabic and ArabicToRoman methods to convert between Arabic and Roman numerals. See that example for a description of those methods.

This example creates extension methods to make the conversions a little easier to use. The following code shows the RomanNumerals class that defines extension methods.

public static class RomanNumerals
{
    // Convert Arabic to Roman.
    public static string ToRoman(this int arabic)
    {
        return ArabicToRoman(arabic);
    }

    // Convert Roman to Arabic.
    public static int ToArabic(this string roman)
    {
        return RomanToArabic(roman);
    }
    ...
}

The extension methods simply call the RomanToArabic and ArabicToRoman methods to perform the conversions. Those methods are the same as they were in the previous example except they have been changed to static methods so they can be used in the static class.

The new extension methods make using the methods a little easier. The following code shows how the main program converts the value you input between Arabic and Roman numerals.

// Convert.
private void btnConvert_Click(object sender, EventArgs e)
{
    // See if we have an Arabic or Roman input.
    if (txtArabic.Text.Length > 0)
    {
        int arabic = int.Parse(txtArabic.Text);
        string roman = arabic.ToRoman();
        int recovered = roman.ToArabic();

        txtRecoveredRoman.Text = roman;
        txtRecoveredArabic.Text = recovered.ToString();
    }
    else
    {
        string roman = txtRoman.Text;
        int arabic = roman.ToArabic();
        string recovered = arabic.ToRoman();

        txtRecoveredRoman.Text = recovered;
        txtRecoveredArabic.Text = arabic.ToString();
    }

    txtArabic.Clear();
    txtRoman.Clear();
}

If the Arabic text box contains text, the program parses it’s contents to get a number. It then uses the ToRoman extension method to convert the number into Roman numerals. It then uses the ToArabic extension method to convert the Roman numerals back into an integer value.

If the Arabic text box is blank, the program uses the extension methods in the other order to convert from Roman numerals into an Arabic value and back.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.

This entry was posted in algorithms, extension methods, mathematics and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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