C# Source Code: Check to see if an enum contains a valid value
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Check to see if an enum contains a valid value
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Thursday, November 04, 2004
Hits:
3302
Category:
General/Framework
Article:
The code below demonstrates how to manually iterate over all the value in an enum to check if an instance of an enum contains a valid value. Note, a second example at the bottom of this post shows you how to use the Enum.IsDefined function. ///
/// Checks to see if a value is valid for the specified enum. This is necessary as DotNet will not /// throw an exception if you assign an invalid value. ///
///
The potential value for this enum - should be of the type of the enumeration to test. ///
Returns true if the enum contains a valid value, else returns false
///
/// public enum MyEnumType : int /// { /// ValidValue = 1 /// } /// ... /// MyEnumType myValue = (MyEnumType)2; // Will not throw an error. /// if ( !EnumValid(myValue) ) /// { /// // Enum value has been detected as invalid. /// } ///
public static bool EnumValid(Enum testValue) { // Cast enum value to an int int testInt = Convert.ToInt32(testValue); // Get array of possible values System.Array values = Enum.GetValues(testValue.GetType()); for ( int index=0; index < values.Length; index++ ) { // Test if value matches if( testInt == (int)values.GetValue(index)) { //Found value return true; } } //Failed to find value return false; } ///
/// Checks to see if a value is valid for the specified enum. This is necessary as DotNet will not /// throw an exception if you assign an invalid value. ///
///
The potential value for this enum - should be of the type of the enumeration to test. ///
Returns true if the enum contains a valid value, else returns false
///
/// public enum MyEnumType : int /// { /// ValidValue = 1 /// } /// ... /// MyEnumType myValue = (MyEnumType)2; // Will not throw an error. /// if ( !EnumValid2(myValue) ) /// { /// // Enum value has been detected as invalid. /// } ///
public static bool EnumValid2(Enum testValue) { // Get the type and check its value is defined return Enum.IsDefined(testValue.GetType(), System.Convert.ToInt32(testValue) }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet