Skip to content

Instantly share code, notes, and snippets.

@AnthonyMastrean
Created June 4, 2012 14:30
Show Gist options
  • Save AnthonyMastrean/2868732 to your computer and use it in GitHub Desktop.
Save AnthonyMastrean/2868732 to your computer and use it in GitHub Desktop.
Type Safe Enum helper methods.
public class Index
{
public static Index One = new Index(1);
public static Index Two = new Index(2);
public static Index Three = new Index(3);
public int Value { get; private set; }
public Index(int value)
{
Value = value;
}
}
TypeSafeEnum.All<Index>().Where(x => x.Value == 3);
public static class TypeSafeEnum
{
/// <summary>
/// Get all instances of the type safe enum. Probably to do some LINQ on the results.
/// </summary>
public static IEnumerable<T> All<T>()
{
var target = typeof(T);
return target
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(x => x.FieldType == target)
.Select(x => x.GetValue(null))
.Cast<T>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment