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");
}
}
}
Which produces the following output -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");
}
}
}
Which now produces the following output -