Created
June 4, 2012 14:30
-
-
Save AnthonyMastrean/2868732 to your computer and use it in GitHub Desktop.
Type Safe Enum helper methods.
This file contains 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 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; | |
} | |
} |
This file contains 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
TypeSafeEnum.All<Index>().Where(x => x.Value == 3); |
This file contains 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 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