tags:

views:

227

answers:

4
enum Answer : int { Yes = 1, No = 2 }
Answer answer = (Answer)100;

It throws, but I don't want it to. How?

+7  A: 

No, it does not throw. Your typecast line does exactly what you want.

Additional:

enums are purposely relaxed about accepting 'invalid' values, this is necessary when using bit-flags.

Henk Holterman
Yes- I would add though what you want is probably an entry for daily WTF!
RichardOD
Ricard, it is an example and not that far of, `answer = (Answer)3` for Yes and No would make some (sort of) sense.
Henk Holterman
A: 

This goes against the concept of enums... They exist to ensure that the option exists. If you need 100 different values my advice is to loose the enum. If you just need "another value" you could do this:

enum Answer : int { Yes = 1, No = 2, OtherValue }
Answer answer = Answer.OtherValue;
Sergio
+1 for a sensible suggestion
RichardOD
A: 

Why would you want to do this? Why not simply use an int if you are not using the features of the enum?

That said, the code does not pose any problem for me:

Answer answer = (Answer)100;
Console.WriteLine(answer); // prints 100
Fredrik Mörk
A: 

Huh, it throws? Are you sure you are using C#? This code is perfectly valid and does what you want it to do!

Maximilian Mayerl