-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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