Skip to content

Instantly share code, notes, and snippets.

@alowdon alowdon/Enum_IsDefined_example.cs Secret
Last active Nov 12, 2018

Embed
What would you like to do?
An example of an unsafe use of Enum.IsDefined, checking enum values in a non-backwards compatible way.
using System;
using System.Linq;
public enum MyEnum
{
A,
B
// introducing a new value C here would cause an argument exception to be thrown in SafeMethod, but not in UnsafeMethod
}
public class MyClass
{
public void SafeMethod(int value)
{
// safe, as it explicitly specifies supported values
if (!(new[] { MyEnum.A, MyEnum.B }).Contains((MyEnum)value))
{
throw new ArgumentException("Supplied value is not supported", nameof(value));
}
...
}
public void UnsafeMethod(int value)
{
// unsafe, as values introduced in the future would also pass this check
if (!Enum.IsDefined(typeof(MyEnum), value))
{
throw new ArgumentException("Supplied value is not supported", nameof(e));
}
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.