Avatar of Scott Baldridge
Scott Baldridge
 asked on

String Enum

Hello, I have an enum like so:

 public enum PermissionType
    {
  [EnumValueName("Paid Customer")]
        PaidCustomer
    }


If I have "Paid Customer" how do I get PaidCustomer?
C#.NET Programming

Avatar of undefined
Last Comment
p_davis

8/22/2022 - Mon
Éric Moreau

p_davis

Does ToString() not work?
Jacques Bourgeois (James Burger)

What is EnumValueName? This is not something that is documented, so I do not know how to use it to get the reference.

But assuming a variable named permission that has the proper value:

permission.ToString()
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
it_saige

Using reflection:
using System;

namespace EE_Q28869700
{
	class Program
	{
		static void Main(string[] args)
		{
			var value = "Paid Customer".GetValueFromEnumValueName<PermissionType>();
			Console.WriteLine(value);
			Console.ReadLine();
		}
	}

	enum PermissionType
	{
		[EnumValueName("Paid Customer")]
		PaidCustomer
	}

	class EnumValueNameAttribute : Attribute
	{
		public string Name { get; set; }

		public EnumValueNameAttribute() { ;}
		public EnumValueNameAttribute(string name)
		{
			Name = name;
		}
	}

	static class Extensions
	{
		public static T GetValueFromEnumValueName<T>(this string name)
		{
			var type = typeof(T);
			if (!type.IsEnum) 
				throw new InvalidOperationException();

			foreach (var field in type.GetFields())
			{
				var attribute = Attribute.GetCustomAttribute(field, typeof(EnumValueNameAttribute)) as EnumValueNameAttribute;
				if (attribute != null)
				{
					if (attribute.Name == name)
						return (T)field.GetValue(null);
				}
				else
				{
					if (field.Name == name)
						return (T)field.GetValue(null);
				}
			}
			throw new ArgumentException("Not found.", "name");
		}
	}
}

Open in new window

Which produces the following output -Capture.JPG-saige-
it_saige

A more *non-intuitive* selection:
using System;
using System.ComponentModel;

namespace EE_Q28869700
{
	class Program
	{
		static void Main(string[] args)
		{
			var value = "Paid Customer".GetValueFromEnumValueName<PermissionType>();
			Console.WriteLine(value);
			value = "Egads".GetValueFromEnumValueName<PermissionType>();
			Console.WriteLine(value);
			Console.ReadLine();
		}
	}

	enum PermissionType
	{
		[EnumValueName("Paid Customer")]
		PaidCustomer,
		[EnumValueName("Egads")]
		UnpaidCustomer
	}

	class EnumValueNameAttribute : Attribute
	{
		public string Name { get; set; }

		public EnumValueNameAttribute() { ;}
		public EnumValueNameAttribute(string name)
		{
			Name = name;
		}
	}

	static class Extensions
	{
		public static T GetValueFromEnumValueName<T>(this string name)
		{
			var type = typeof(T);
			if (!type.IsEnum) 
				throw new InvalidOperationException();

			foreach (var field in type.GetFields())
			{
				var attribute = Attribute.GetCustomAttribute(field, typeof(EnumValueNameAttribute)) as EnumValueNameAttribute;
				if (attribute != null)
				{
					if (attribute.Name == name)
						return (T)field.GetValue(null);
				}
				else
				{
					if (field.Name == name)
						return (T)field.GetValue(null);
				}
			}
			throw new ArgumentException("Not found.", "name");
		}
	}
}

Open in new window

Which now produces the following output -Capture.JPG-saige-
Scott Baldridge

ASKER
I tried to get PaidCustomer like this :

string permissionName = Roles.GetPermissionName(permissionId);
//permissionName = "Paid Customer"

 PermissionType permission =  (PermissionType) Enum.Parse(typeof(PermissionType), permissionName);

but get this error: Requested value 'Paid Customer' was not found.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
it_saige

Correct, Parse will only work if the string matches the enum value.  This is where the extension method plays it's role in order to match the string value with the EnumValueName attribute.

-saige-
ASKER CERTIFIED SOLUTION
it_saige

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Scott Baldridge

ASKER
Thank you! I'm going to give it a go!
Jacques Bourgeois (James Burger)

@it_saige

Where did you get the documentation for the EnumValueName attribute? I cannot find it anywhere, even by googling it.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Scott Baldridge

ASKER
WOW! that is the way to go! Works perfectly!
it_saige

I just assumed it was a custom attribute since it was enclosed in Attribute declarative markup.  From there, the attributes constructor accepts a string so I just assumed that the string's property was Name since the attributes name was EnumValueName.

-saige-
it_saige

Glad that worked out for you Earnie.

-saige-
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
p_davis

@Jacques Bourgeois... I believe that it is a custom attribute. I think i remember a project online somewhere..... if i find it i will post.
p_davis

i know i shouldn't post a link here but...

http://www.codeproject.com/Articles/11130/String-Enumerations-in-C