Thanks for the Roman Numeral example! I made some equivalent functions in C# using Enum's static methods. This results in more concise versions of the two primary methods described in the article. They have been named a little bit differently to suit my tastes, but are the same methods in terms of the algorithm used. This code also uses the exact same RomanNumerals enum (which I haven't included in this snippet). Feel free to suggest further improvements, or to translate this back to VB.NET:
private int ParseRomanNumeral(string numeral)
{
numeral = numeral.ToUpper();
char[] characters = numeral.ToCharArray();
int[] parseBuf = new int[numeral.Length];
int result = 0;
bool bSkip = false;
for (int i = numeral.Length - 1; i >= 0; i--)
{
if (bSkip)
{
bSkip = false; // Skip this digit because it is part of a 2-digit numeral
continue;
}
parseBuf[i] = (int)Enum.Parse(typeof(RomanNumerals), characters[i].ToString());
if (parseBuf[i] % 5 == 0 && i > 0)
{
string extended = characters[i-1].ToString() + characters[i].ToString();
try
{
parseBuf[i] = (int)Enum.Parse(typeof(RomanNumerals), extended);
bSkip = true;
}
catch(ArgumentException)
{
// Ignore this exception. It just means we didn't find an extended numeral
}
}
}
for (int i = 0; i < numeral.Length; i++)
{
result += parseBuf[i];
}
return result;
}
private string ConvertToRomanNumeral(int num)
{
string sResult = "";
sResult = Enum.GetName(typeof(RomanNumerals), num);
if (sResult == null)
{
string[] names = Enum.GetNames(typeof(RomanNumerals));
int[] vals = (int[])Enum.GetValues(typeof(RomanNumerals));
for (int i = names.Length - 1; i > 0; i--) // Don't process the 0th element, since it is 0 and results in bad math
{
int temp = num / vals[i];
num -= temp * vals[i];
for (int j = 0; j < temp; j++)
{
sResult += names[i];
}
}
}
return sResult;
}