Created
August 15, 2013 06:27
-
-
Save yemrekeskin/6238708 to your computer and use it in GitHub Desktop.
Enum String Values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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