Skip to content

Feature request: Guard.IsDefined<TEnum>() #482

Description

@ovska

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

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature request 📬A request for new changes to improve functionality

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions