enum Fruit
{
Banana,
Orange,
Strawberry
...
...
// etc, very long enum
}
PeelFruit(Fruit.Orange);
PeelFruit(Fruit.Banana);
PeelFruit(Fruit.Strawberry); // huh? can't peel strawberries!
Sorry for the lame example, but hopefully you get the idea. Is there a way to constrain the enum values that PeelFruit will accept?
Obvisouly I could check them in the method with a switch or something, but it would be cool if there was a way to do it that is a) a bit more compact, and b) would cause a compile time error, not a run time error.
[Fruit = Orange,Bannana]
void PeelFruit(Fruit fruit) { ... }
This isn’t possible with base language features (it’s possible with code contracts, though compile-time checking is only available with the premium edition). In fact you can’t even constrain your input to the values defined in your
enum! A method that accepts aFruitparameter will accept anyint(or whatever the enumeration’s type is, if it isn’t an integer), as long as the caller casts it toFruitfirst: