-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Closed
Labels
api-suggestionEarly API idea and discussion, it is NOT ready for implementationEarly API idea and discussion, it is NOT ready for implementationarea-System.Runtime
Description
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
Labels
api-suggestionEarly API idea and discussion, it is NOT ready for implementationEarly API idea and discussion, it is NOT ready for implementationarea-System.Runtime