Just out of curiosity, asking this
Like the expression one below
a = (condition) ? x : y; // two outputs
why can't we have an operator for enums?
say,
myValue = f ??? fnApple() : fnMango() : fnOrange(); // no. of outputs specified in the enum definition
instead of switch statements (even though refactoring is possible)
enum Fruit
{
apple,
mango,
orange
};
Fruit f = Fruit.apple;
Or is it some kind of useless operator?
I can't say I've ever wanted such an operator - which would be incredibly brittle by relying on the ordering of the enum values. You can easily use a switch:
switch (f)
{
case Fruit.Apple: myValue = fnApple(); break;
case Fruit.Mango: myValue = fnMango(); break;
case Fruit.Orange: myValue = fnOrange(); break;
default: throw new ArgumentOutOfRangeException("f");
}
Alternatively, create a map:
static readonly Dictionary<Fruit, Func<Foo>> FruitFunctions =
new Dictionary<Fruit, Func<Foo>> {
{ Fruit.Apple, fnApple },
{ Fruit.Mango, fnMango },
{ Fruit.Orange, fnOrange }
};
...
myValue = FruitFunctions[f]();
I've used both techniques in various situations, and far prefer them to the suggested operator, I'm afraid.
Offhand I can think of three reasons:
C# borrows syntax from C++, and C++ borrows syntax from C, and C didn't have a ???:::
operator, because K&R probably didn't feel like it was necessary. It's not a "useless operator", but it would be considered syntactic sugar.
Moreover, it's not a good idea for an operator to rely on the particular ordering of constants in the enum declaration.
condition is evaluated to true or false. What is proposed algorithm of your non-existing operator? It is difficult to say whether it may be useful or not, but switch-case can do what you need.
The main problem - apart from it being unsafe, unnecessary, and probably unreadable in most real cases - is that it promotes a programming model that most people would these days regard as bad.
Most languages have programming/design styles they allow and those they want to promote. C# allows imperative and procedural programming but promotes the use of object oriented techniques. Your operator belongs firmly in the first camp and is not something that the designers of the language would want to support.
If you did want to program in that style then you could use:
myValue = (f == Fruit.apple) ? fnApple()
: (f == Fruit.mango) ? fnMango()
: fnOrange();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.