Created
November 28, 2023 16:41
-
-
Save adamijak/0ab78a4334f4a8c40b1f971079f3120a 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
namespace _; | |
public class EnumBinding<T> where T : struct, Enum | |
{ | |
private const bool IgnoreCase = true; | |
private const bool IgnoreInt = true; | |
private T value; | |
public static bool TryParse(string value, out EnumBinding<T> result) | |
{ | |
return TryParse(value, null!, out result); | |
} | |
public static bool TryParse(string value, IFormatProvider provider, out EnumBinding<T> result) | |
{ | |
result = new EnumBinding<T>(); | |
if (IgnoreInt && int.TryParse(value, out _)) | |
{ | |
return false; | |
} | |
var success = Enum.TryParse(value, IgnoreCase, out T parsedValue); | |
if (!success || !Enum.IsDefined(typeof(T), parsedValue)) | |
{ | |
return false; | |
} | |
result.value = parsedValue; | |
return true; | |
} | |
public static implicit operator T(EnumBinding<T> e) => e.value; | |
public override string ToString() => value.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: