Skip to content

Instantly share code, notes, and snippets.

@WrackedFella
Last active October 9, 2019 17:41
Show Gist options
  • Save WrackedFella/b4f94b665e401f104ad5936e81698567 to your computer and use it in GitHub Desktop.
Save WrackedFella/b4f94b665e401f104ad5936e81698567 to your computer and use it in GitHub Desktop.
public sealed class Status : TypeSafeEnum
{
private static readonly Dictionary<int, Status> Instance = new Dictionary<int, Status>();
public static readonly Status Active = new Status(0, "Active", 'A');
public static readonly Status Inactive = new Status(1, "InActive", 'I');
private Status(int value, string name, char code) : base(value, name, code)
{
Instance[value] = this;
}
public static explicit operator Status(int value)
{
if (Instance.TryGetValue(value, out var result))
return result;
else
throw new InvalidCastException();
}
public static explicit operator int(Status v)
{
return v.Value;
}
public static IList<SelectListItem> ToSelectList()
{
return Instance.Select(x => new SelectListItem(x.ToString(), x.Key.ToString())).ToList();
}
}
public abstract class TypeSafeEnum : IComparable
{
public int Value { get; }
public string Name { get; }
public char Code { get; }
protected TypeSafeEnum(int value, string name, char code)
{
this.Value = value;
this.Name = name;
this.Code = code;
}
public override string ToString() => this.Name;
public static IEnumerable<T> GetAll<T>() where T : TypeSafeEnum
{
var fields = typeof(T).GetFields(BindingFlags.Public |
BindingFlags.Static |
BindingFlags.DeclaredOnly);
return fields.Select(f => f.GetValue(null)).Cast<T>();
}
public override bool Equals(object obj)
{
var otherValue = obj as TypeSafeEnum;
if (otherValue == null)
return false;
var typeMatches = GetType() == obj.GetType();
var valueMatches = this.Value.Equals(otherValue.Value);
return typeMatches && valueMatches;
}
public int CompareTo(object other) => this.Value.CompareTo(((TypeSafeEnum)other).Value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment