Skip to content

Instantly share code, notes, and snippets.

@zoint zoint/EnumExtensions.cs
Last active Aug 29, 2015

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace MadWorldApps.PCL.Helpers.Extensions
{
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);
}
public static IEnumerable<string> GetNamesWithSpaces<TEnum>() where TEnum : struct
{
var typeInfo = ValidateEnum<TEnum>();
return typeInfo.DeclaredFields.Where(f => f.IsLiteral && (f.IsPublic | f.IsStatic))
.Select(f => f.Name.AddSpacesToWord());
}
/// <summary>
/// Cleans the string and attempts to convert it to an enum.
/// </summary>
/// <typeparam name="TEnum">A valid enum type that you want the string converted to.</typeparam>
/// <param name="enumString">The member of the enum you want to return.</param>
/// <returns>The matching enum member based on the input string.</returns>
public static TEnum GetEnumValueFromString<TEnum>(string enumString) where TEnum : struct
{
ValidateEnum<TEnum>();
var cleanString = enumString.RemoveSpacesFromWords();
TEnum newEnum;
if (Enum.TryParse(cleanString, true, out newEnum)) return newEnum;
throw new ArgumentException(string.Format("Provided enumString is not a valid Enum member."));
}
/// <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
You can’t perform that action at this time.