Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Enum.ToString() with complete name

Tags:

c#

enums

tostring

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;

// This will always get "Red" but I need "Color.Red"
string colorString = color.ToString();

// I know that this is what I need:
colorString = Color.Red.ToString();

So is there a solution?

like image 578
Franki1986 Avatar asked Sep 19 '13 09:09

Franki1986


2 Answers

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

like image 81
Alireza Avatar answered Sep 26 '22 00:09

Alireza


Try this:

        Color color = Color.Red;

        string colorString = color.GetType().Name + "." + Enum.GetName(typeof(Color), color);
like image 42
stevepkr84 Avatar answered Sep 22 '22 00:09

stevepkr84