Skip to content

Instantly share code, notes, and snippets.

@alowdon
Last active November 12, 2018 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alowdon/f7354cda97bac70b44e1c04bc0991bcc to your computer and use it in GitHub Desktop.
Save alowdon/f7354cda97bac70b44e1c04bc0991bcc to your computer and use it in GitHub Desktop.
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