Skip to content

Instantly share code, notes, and snippets.

@zoint
Created February 4, 2014 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoint/8798242 to your computer and use it in GitHub Desktop.
Save zoint/8798242 to your computer and use it in GitHub Desktop.
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