Title: 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)
// Convert Roman to Arabic.
public static int ToArabic(this string 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.
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();
string roman = txtRoman.Text;
int arabic = roman.ToArabic();
string recovered = arabic.ToRoman();
txtRecoveredRoman.Text = recovered;
txtRecoveredArabic.Text = arabic.ToString();
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 the example to experiment with it and to see additional details.