Created
June 2, 2017 16:58
-
-
Save crissilvaeng/739f0754da388a611a6e2ee63ff90595 to your computer and use it in GitHub Desktop.
Enum to custom string!
This file contains 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
using System; | |
using System.ComponentModel; | |
using System.Linq; | |
using System.Reflection; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(Batata.Frita.ToDescription()); | |
Console.WriteLine(Molho.Ketchup.ToDescription()); | |
Console.ReadKey(); | |
} | |
} | |
public enum Batata | |
{ | |
[Description("Batata Frita")] | |
Frita = 1, | |
[Description("Batata Frita")] | |
Assada = 2 | |
} | |
public enum Molho | |
{ | |
[Description("Ketchup Especial")] | |
Ketchup = 1, | |
[Description("Mostarda Preta")] | |
Mostarda = 2 | |
} | |
public static class EnumerationExtension | |
{ | |
public static string ToDescription<T>(this T enumeration) where T : struct | |
{ | |
Type type = enumeration.GetType(); | |
if (type.IsEnum != true) | |
{ | |
throw new ArgumentException("Enumeration must be of Enum type", "enumeration"); | |
} | |
MemberInfo[] info = type.GetMember(enumeration.ToString()); | |
if (info != null && info.Any() == true) | |
{ | |
object[] attrs = info.First().GetCustomAttributes(typeof(DescriptionAttribute), false); | |
if (attrs != null && attrs.Any() == true) | |
{ | |
return ((DescriptionAttribute)attrs.First()).Description; | |
} | |
} | |
return enumeration.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment