Skip to content

Instantly share code, notes, and snippets.

@yemrekeskin
Created August 15, 2013 06:27
Show Gist options
  • Save yemrekeskin/6238708 to your computer and use it in GitHub Desktop.
Save yemrekeskin/6238708 to your computer and use it in GitHub Desktop.
Enum String Values
public class StringValueAttribute
: Attribute
{
public string StringValue { get; protected set; }
public StringValueAttribute(string value)
{
StringValue = value;
}
}
public enum PaymentType
{
[StringValue("Foreign Payment")]
Foreign = 0,
[StringValue("Domestic Payment")]
Domestic = 1,
[StringValue("Sepa Payment")]
Sepa = 2,
[StringValue("Other Payment Types")]
Other = 3
}
public static class EnumExtention
{
public static string GetStringValue(this Enum value)
{
Type type = value.GetType();
FieldInfo fieldInfo = type.GetField(value.ToString());
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
return attribs != null && attribs.Length > 0 ? attribs[0].StringValue : null;
}
}
//Let's use it
class Program
{
static void Main(string[] args)
{
PaymentType type = PaymentType.Foreign;
Console.WriteLine(type.GetStringValue());
PaymentType type1 = PaymentType.Sepa;
Console.WriteLine(type1.GetStringValue());
PaymentType type2 = PaymentType.Domestic;
Console.WriteLine(type2.GetStringValue());
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment