Skip to content

Instantly share code, notes, and snippets.

@Fusion86
Last active February 16, 2018 20:23
Show Gist options
  • Save Fusion86/9dbeb113dac40c5894987113b50a4b32 to your computer and use it in GitHub Desktop.
Save Fusion86/9dbeb113dac40c5894987113b50a4b32 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Reflection;
namespace Ayra.Core.Enums
{
// Based on https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/
public abstract class Enumeration : IComparable
{
public readonly int Id;
public readonly string Name;
public Enumeration() { }
protected Enumeration(int id, string name)
{
Id = id;
Name = name;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
public override string ToString()
{
return Name;
}
public static IEnumerable<T> GetAll<T>() where T : Enumeration, new()
{
var type = typeof(T);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
foreach (var info in fields)
{
var instance = new T();
if (info.GetValue(instance) is T locatedValue)
{
yield return locatedValue;
}
}
}
public int CompareTo(object obj)
{
return Id.CompareTo(((Enumeration)obj).Id);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment