Tuesday, April 05, 2005
String Enumerators
using System;
using System.Reflection;
enum EnumError
{
OverLimit,
UnderLimit,
Normal,
}
class EnumErrorDescriptions
{
const string OverLimit = "Oh you have exceeds your limit!";
const string UnderLimit = "Oh! you are much below your limit!";
const string Normal = "Oh! you are within your limit!";
internal static string GetErrorMessage (EnumError err)
{
string enumName = err.ToString();
FieldInfo fi = typeof(EnumErrorDescriptions).GetField
(enumName, BindingFlags.Static|BindingFlags.NonPublic);
if (fi==null)
{
// Oops! You could throw an exception here if you wanted -
// or return another constant, maybe.
return "Unknown error";
}
return (string)fi.GetValue(null);
}
}
class Test
{
static void Main()
{
Console.WriteLine (EnumErrorDescriptions.GetErrorMessage
(EnumError.OverLimit));
}
}
Basically enum provides only integer values, but through this mechanism you can get string values through enum (string enumeration).
With Best Regards,
Mitesh V. Mehta
using System.Reflection;
enum EnumError
{
OverLimit,
UnderLimit,
Normal,
}
class EnumErrorDescriptions
{
const string OverLimit = "Oh you have exceeds your limit!";
const string UnderLimit = "Oh! you are much below your limit!";
const string Normal = "Oh! you are within your limit!";
internal static string GetErrorMessage (EnumError err)
{
string enumName = err.ToString();
FieldInfo fi = typeof(EnumErrorDescriptions).GetField
(enumName, BindingFlags.Static|BindingFlags.NonPublic);
if (fi==null)
{
// Oops! You could throw an exception here if you wanted -
// or return another constant, maybe.
return "Unknown error";
}
return (string)fi.GetValue(null);
}
}
class Test
{
static void Main()
{
Console.WriteLine (EnumErrorDescriptions.GetErrorMessage
(EnumError.OverLimit));
}
}
Basically enum provides only integer values, but through this mechanism you can get string values through enum (string enumeration).
With Best Regards,
Mitesh V. Mehta