Skip to content

Instantly share code, notes, and snippets.

@adamijak
Created November 28, 2023 16:41
Show Gist options
  • Save adamijak/0ab78a4334f4a8c40b1f971079f3120a to your computer and use it in GitHub Desktop.
Save adamijak/0ab78a4334f4a8c40b1f971079f3120a to your computer and use it in GitHub Desktop.
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();
}
@adamijak
Copy link
Author

adamijak commented Dec 5, 2023

Example usage:

app.MapGet("/", ([FromQuery] EnumBinding<MyEnum> param) => 
{
   MyEnum enumValue = param;
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment