Last active
June 30, 2021 03:53
-
-
Save bryanknox/77c5c7117fc5532fdbccf3178c7e666c to your computer and use it in GitHub Desktop.
Parse an enum value from a string in C#
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
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