Skip to content

Instantly share code, notes, and snippets.

@bryanknox
Last active June 30, 2021 03:53
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 bryanknox/77c5c7117fc5532fdbccf3178c7e666c to your computer and use it in GitHub Desktop.
Save bryanknox/77c5c7117fc5532fdbccf3178c7e666c to your computer and use it in GitHub Desktop.
Parse an enum value from a string in C#
using System;
namespace K0x.Utilities
{
public static class EnumParseUtils
{
/// <summary>
/// Try to parse an enum value from the given string.
/// </summary>
/// <typeparam name="TEnum">
/// The type of the enum.
/// </typeparam>
/// <param name="text">
/// The string to be parsed. For success the string will match (case insenstive)
/// one of the named valued defined in TEnum or its int equivelent value.
/// </param>
/// <param name="enumValue">
/// The TEnum value parsed if successful. It will be one of the names
/// defined for the TEnum.
/// </param>
/// <returns>
/// Returns true if a TEnum could be parsed from the given string.
/// </returns>
public static bool TryParseEnum<TEnum>(string text, out TEnum enumValue)
where TEnum : struct
{
bool isEnumValue = Enum.TryParse<TEnum>(
text,
ignoreCase: true,
out enumValue);
if (isEnumValue)
{
if (int.TryParse(text, out int intValue))
{
// The value is an int.
if (Enum.IsDefined(typeof(TEnum), intValue))
{
// The int value is a valid value for the enum.
// So get the equivelent enum value.
enumValue = (TEnum)(object)intValue;
}
else
{
// The int value is NOT a valid value for the enum.
isEnumValue = false;
}
}
}
return isEnumValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment