Created
June 28, 2018 15:21
-
-
Save majstudio/f7f2bfa355853fe4d576d8bec483c5bd to your computer and use it in GitHub Desktop.
Java-style enum in C# workaround
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 EnumFieldAttribute : Attribute | |
{ | |
private object value{get; set;} | |
public EnumFieldAttribute(object val) | |
{ | |
value = val; | |
} | |
public T GetValue<T>() | |
{ | |
return (T)value; | |
} | |
} | |
public static class EnumHandler | |
{ | |
public static T GetAttributeOfType<T>(this Enum enumVal) where T : System.Attribute | |
{ | |
var type = enumVal.GetType(); | |
var memInfo = type.GetMember(enumVal.ToString()); | |
var attributes = memInfo[0].GetCustomAttributes(typeof(T), false); | |
return (attributes.Length > 0) ? (T)attributes[0] : null; | |
} | |
public static T GetEnumFieldValue<T>(this Enum enumVal) | |
{ | |
return enumVal.GetAttributeOfType<EnumFieldAttribute>().GetValue<T>(); | |
} | |
} |
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
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Displays 8 | |
Console.WriteLine(Insects.Spider.GetEnumFieldValue<int>()); | |
} | |
//We can store any type of objects into our enum values | |
//This time we choose int to represent the number of legs for example | |
enum Insects | |
{ | |
[EnumField(8)] | |
Spider, | |
[EnumField(10)] | |
Caterpillar, | |
[EnumField(6)] | |
Grasshoper | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment