Skip to content

[API Proposal]: Add InvalidEnumArgumentException.ThrowIfUndefined #92071

@Abrynos

Description

@Abrynos

Background and motivation

In the past years we've received multiple new methods such as ArgumentNullException.ThrowIfNull, ArgumentException.ThrowIfNullOrEmpty, ArgumentOutOfRangeException.ThrowIfNegative and many more, but there is none available on InvalidEnumArgumentException.

API Proposal

namespace System.ComponentModel;

public class InvalidEnumArgumentException  : ArgumentException
{
+    public static void ThrowIfUndefined<T>(T argument, [CallerArgumentExpression("argument")] string? argumentName = null) where T : struct, System.Enum
+    {
+        ArgumentException.ThrowIfNullOrEmpty(argumentName);
+        if (!Enum.IsDefined(argument))
+        {
+            throw new InvalidEnumArgumentException(argumentName, (int)(object)argument, typeof(T));
+        }
+    }
}

API Usage

public enum SomeEnumeration {
    SomeValue,
    SomeOtherValue,
}

public void SomeMethod(string str, SomeEnumeration value) {
    ArgumentException.ThrowIfNullOrEmpty(str);
    InvalidEnumArgumentException.ThrowIfUndefined(value);
}

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions