CommunityToolkit / CommunityToolkit/dotnet
Feature request: Guard.IsDefined<TEnum>()
- Dominant language
- C#
- Stars
- 3.8k
- Forks
- 400
- PR merge metrics
- No merged PRs in 30d
Description
### Overview
I've thoroughly enjoyed the usefulness of the `Guard` API, but one thing it's missing is enum validation (for non-flags enums).
The one issue is that the generic `Enum.IsDefined<>` seems to only be available from .NET 5 onwards, which might be the reason this API hasn't made its way yet to the library, and whether silently boxing the value in pre-NET5 builds is an acceptable thing to do for parameter validation.
### API breakdown
Example:
```cs
public static void IsDefined(TEnum value, [CallerArgumentExpression("value")] string name = "")
where TEnum : struct, Enum
{
if (Enum.IsDefined(value))
return;
ThrowHelper.ThrowArgumentOutOfRangeException(name, value, null); // or a descriptive message
}
```
### Usage example
```cs
public class Something
{
public DayOfWeek Value { get; }
public Something(DayOfWeek value)
{
Guard.IsDefined(value);
Value = value;
}
}
```
### Breaking change?
No
### Alternatives
User can call `IsDefined` and `ThrowArgumentOutOfRangeException` or `ThrowArgumentException` directly.
### Additional context
Not sure if `IsDefined` or `IsEnumDefined` is a better value.
### Help us help you
Yes, I'd like to be assigned to work on this item
Contributor guide
Assessment
This issue has not been assessed yet.