Created
February 4, 2014 04:39
-
-
Save zoint/8798242 to your computer and use it in GitHub Desktop.
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 EnumExtensions | |
{ | |
/// <summary> | |
/// Converts the enum member names into an enumberable of strings. | |
/// </summary> | |
/// <typeparam name="TEnum">A valid enum type.</typeparam> | |
/// <returns>An enumerable of strings based on the enum members.</returns> | |
public static IEnumerable<string> GetNames<TEnum>() where TEnum : struct | |
{ | |
var typeInfo = ValidateEnum<TEnum>(); | |
return typeInfo.DeclaredFields.Where(f => f.IsLiteral && (f.IsPublic | f.IsStatic)).Select(f => f.Name); | |
} | |
/// <summary> | |
/// Validates that the type is a valid enum, throws an ArgumentException if not. | |
/// </summary> | |
/// <typeparam name="TEnum">A valid enum type.</typeparam> | |
/// <returns>Returns the typeinfo for the enum if a valid enum was specified.</returns> | |
private static TypeInfo ValidateEnum<TEnum>() | |
{ | |
var type = typeof(TEnum); | |
var typeInfo = type.GetTypeInfo(); | |
if (!typeInfo.IsEnum) | |
throw new ArgumentException(String.Format("Type '{0}' is not an enum", type.Name)); | |
return typeInfo; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment