I've read a few SO posts and it seems most basic operation is missing.
public enum LoggingLevel { Off = 0, Error = 1, Warning = 2, Info = 3, Debug = 4, Trace = 5 }; if (s == "LogLevel") { _log.LogLevel = (LoggingLevel)Convert.ToInt32("78"); _log.LogLevel = (LoggingLevel)Enum.Parse(typeof(LoggingLevel), "78"); _log.WriteDebug(_log.LogLevel.ToString()); }
This causes no exceptions, it's happy to store 78
. Is there a way to validate a value going into an enum?
In C#, we can check the specific type is enum or not by using the IsEnum property of the Type class. It will return true if the type is enum. Otherwise, this property will return false. It is a read-only property.
Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.
An Enum value cannot be treated as an int by default because then you would be able to provide any integer and there would be no compile time check to validate that the provided integer does in fact exist as a value in the Enumeration.
Check out Enum.IsDefined
Usage:
if(Enum.IsDefined(typeof(MyEnum), value)) MyEnum a = (MyEnum)value;
This is the example from that page:
using System; [Flags] public enum PetType { None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Reptile = 16, Other = 32 }; public class Example { public static void Main() { object value; // Call IsDefined with underlying integral value of member. value = 1; Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value)); // Call IsDefined with invalid underlying integral value. value = 64; Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value)); // Call IsDefined with string containing member name. value = "Rodent"; Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value)); // Call IsDefined with a variable of type PetType. value = PetType.Dog; Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value)); value = PetType.Dog | PetType.Cat; Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value)); // Call IsDefined with uppercase member name. value = "None"; Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value)); value = "NONE"; Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value)); // Call IsDefined with combined value value = PetType.Dog | PetType.Bird; Console.WriteLine("{0:D}: {1}", value, Enum.IsDefined(typeof(PetType), value)); value = value.ToString(); Console.WriteLine("{0:D}: {1}", value, Enum.IsDefined(typeof(PetType), value)); } }
The example displays the following output:
// 1: True // 64: False // Rodent: True // Dog: True // Dog, Cat: False // None: True // NONE: False // 9: False // Dog, Bird: False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With