Skip to content

Instantly share code, notes, and snippets.

@majstudio
Created June 28, 2018 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save majstudio/f7f2bfa355853fe4d576d8bec483c5bd to your computer and use it in GitHub Desktop.
Save majstudio/f7f2bfa355853fe4d576d8bec483c5bd to your computer and use it in GitHub Desktop.
Java-style enum in C# workaround
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>();
}
}
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