Here are two options for solving this issue:
- Build a
Dictionary<Country, string>
- Use the
Country
enumeration and decorate it with a Description
attribute
Build a Dictionary<Country, string>
, like this:
enum Country
{
UnitedStates,
Germany,
Hungary
}
Dictionary<Country, string> CountryNames = new Dictionary<Country, string>
{
{ Country.UnitedStates, "US" },
{ Country.Germany, "DE" }
{ Country.Hungary, "HU" }
};
static string ConvertCountry(Country country)
{
string name;
return (CountryNames.TryGetValue(country, out name))
? name : country.ToString();
}
Now you can use the Dictionary<Country, string>
via the static ConvertCountry
method, like this:
var myCountry = ConvertCountry(Country.UnitedStates));
Use the Country
enumeration and decorate it with a Description
attribute, like this:
enum Country
{
[Description("US")]
UnitedStates,
[Description("DE")]
Germany,
[Description("HU")]
Hungary
}
Now you can use this method to get a Description
attribute value, like this:
public static string GetDescription(Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((DescriptionAttribute)attrs[0]).Description;
}
}
return en.ToString();
}
Usage of above method, like this:
var myCountryDescription = GetDescription(Country.UnitedStates);