I am searching a solution to get the complete String of an enum.
Example:
Public Enum Color
{
Red = 1,
Blue = 2
}
Color color = Color.Red;
/
Try this:
Color color = Color.Red;
string colorString = color.GetType().Name + "." + Enum.GetName(typeof(Color), color);
colorString = color.GetType().Name + "." + color.ToString();
Fast variant that works for every enum
public static class EnumUtil<TEnum> where TEnum : struct
{
public static readonly Dictionary<TEnum, string> _cache;
static EnumUtil()
{
_cache = Enum
.GetValues(typeof(TEnum))
.Cast<TEnum>()
.ToDictionary(x => x, x => string.Format("{0}.{1}", typeof(TEnum).Name, x));
}
public static string AsString(TEnum value)
{
return _cache[value];
}
}
I have no idea if this is the best way, but it works:
string colorString = string.Format("{0}.{1}", color.GetType().FullName, color.ToString())
You can use extension methods.
public static class EnumExtension
{
public static string ToCompleteName(this Color c)
{
return "Color." + c.ToString();
}
}
Now method below will return "Color.Red".
color.ToCompleteName();
http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx
public static class Extensions
{
public static string GetFullName(this Enum myEnum)
{
return string.Format("{0}.{1}", myEnum.GetType().Name, myEnum.ToString());
}
}
usage:
Color color = Color.Red;
string fullName = color.GetFullName();
Note: I think GetType().Name
is better that GetType().FullName