[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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) { 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.