Skip to content

[API Proposal]: Add InvalidEnumArgumentException.ThrowIfNotDefined #83107

@RichardRobertson

Description

@RichardRobertson

Background and motivation

Checking enum arguments for validity requires some boilerplate and would benefit from a convenience method similar to ArgumentNullException.ThrowIfNull.

API Proposal

using System;
using System.Runtime.CompilerServices;

namespace System.ComponentModel;

public class InvalidEnumArgumentException : ArgumentException
{
    // existing class body

    public static void ThrowIfNotDefined<TEnum>(TEnum argument, [CallerArgumentExpression(nameof(argument))] string? paramName = default) where TEnum : struct
    {
        if (!Enum.IsDefined(argument))
        {
            throw new InvalidEnumArgumentException(paramName, (int)argument, typeof(TEnum));
        }
    }
}

API Usage

public enum MyEnum
{
    Value1 = 0,
    Value2 = 1
}

public void MyMethod(MyEnum myEnum)
{
    InvalidEnumArgumentException.ThrowIfNotDefined(myEnum);
    // do something with myEnum
}

public void Main()
{
    MyMethod(MyEnum.Value1); // ok
    MyMethod((MyEnum)2); // InvalidEnumArgumentException
}

Alternative Designs

Current practice is to call Enum.IsDefined, and if necessary, throw a new exception. This already works but requires boilerplate code that could be eliminated.

Risks

This new method proposed should not affect any existing API.

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