tags:

views:

148

answers:

4

I've read a few SO posts and it seems most basic operation is missing. CAN IT BE??

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());
}

no exceptions. 78 is happily wrote. this is sad. I read why the cast does not automatically throw error but PLEASE!!! NO way to check it at all. That's just too much...

Thanks & BR -Matti

+11  A: 

Check out Enum.IsDefined
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
SwDevMan81
thanks a lot! couldn't believe it. just wonder what (LoggingLevel)Enum.Parse(typeof(LoggingLevel), "78"); is supposed to do...
matti
@matti: Convert "78" into whatever number representation `LoggingLevel` uses as storage, then present that as a `LoggingLevel` enum value.
thecoop
+3  A: 

Use Enum.IsDefined.

driis
+2  A: 

Use:

Enum.IsDefined ( typeof ( Enum ), EnumValue );
n535
+6  A: 

The canonical answer would be Enum.IsDefined, but that is a: a bit slow if used in a tight loop, and b: not useful for [Flags] enums.

Personally, I'd stop worrying about that, and just switch appropriately, remembering:

  • if it is OK not to recognise everything (and just not do anything), then don't add a default: (or have an empty default: explaining why)
  • if there is a sensible default behaviour, put that in the default:
  • otherwise, handle the ones you know about and throw an exception for the rest:

Like so:

switch(someflag) {
    case TriBool.Yes:
        DoSomething();
        break;
    case TriBool.No:
        DoSomethingElse();
        break;
    case TriBool.FileNotFound:
        DoSomethingOther();
        break;
    default:
        throw new ArgumentOutOfRangeException("someflag");
}
Marc Gravell
not familiar with [Flags] enums and performance is not an issue so your answer seems like the reason why enums were invented in the first place ;) looking at your "points" or whatever they're called so you have to have a point there. Bet you didn't get them for nothing, but think about situation of reading config file where there's 257 values in one enum defition. Let alone dozens of other enums. There would be lots of case-rows...
matti
@matti - that sounds an extreme example; deserialization is a specialist area anyway - most serialization engines offer enum validation for free.
Marc Gravell
@matti - on a side note; I'd say treat answers based on their individual merits. I sometimes get things completely wrong, and somebody with "rep 17" could just as equally give a **perfect** answer.
Marc Gravell
@marc - true :)
matti