Constraining enum value in method parameter

Posted by fearofawhackplanet on Stack Overflow See other posts from Stack Overflow or by fearofawhackplanet
Published on 2010-04-21T19:08:07Z Indexed on 2010/04/21 19:13 UTC
Read the original article Hit count: 285

Filed under:
|
|
|
|
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) { ... }

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET