dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

Feature request: Guard.IsDefined<TEnum>()

Open ovska opened this issue 3 years ago • 1 comments

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:

public static void IsDefined<TEnum>(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

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

ovska avatar Oct 26 '22 13:10 ovska

+1 here.

As for the type of exception to throw, ArgumentException looks more appropriate than ArgumentOutOfRangeException to me, as there is no range necessarily involved.

enum MyEnum
{
    SomeValue = 1,
    SomeOtherValue = 18, // No range to speak of
    YetAnotherValue = 255, // I mean, argument out of... what? :)
}

rdeago avatar Nov 07 '22 11:11 rdeago