Shorter condition statements #1653
-
We all know the following struggle when writing conditions: public enum MyEnum
{
typeA,
typeB,
typeC,
typeD
}
var type = MyEnum.typeA;
if(type != MyEnum.typeB && type != MyEnum.typeC && type != MyEnum.typeD)
{
// do stuff
} Writing the if(type != (MyEnum.typeB && MyEnum.typeC && MyEnum.typeD))
{
// do stuff
} This would also work for other types besides enums like such: var foo = "bar";
if(foo == ("some" || "random" || "value" || "bar"))
{
// do stuff
} It should work for every operator like such: var limitA = 5;
var limitB = 10;
var foo = 15;
if(foo > (limitA && limitB))
{
// do stuff
} Would this be a welcome feature? |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 2 replies
-
This would break existing code as arbitrary types may already overload the |
Beta Was this translation helpful? Give feedback.
-
var foo = "bar";
if (foo is "some" or "random" or "value" or "bar")
{
// do stuff
} |
Beta Was this translation helpful? Give feedback.
-
@ufcpp That is better because it obviously won't be breaking previous code as well as being more closer to English, less parens, and even shorter. |
Beta Was this translation helpful? Give feedback.
-
There's greater precedent for syntax along these lines:
(Inspired by very faded memories of the Delphi enumeration and set syntax) This avoids the need to overload the meaning of But, I'm not sure the language needs this - and I strongly suspect making it work with predictable performance would be challenging. |
Beta Was this translation helpful? Give feedback.
-
I found Flags enums usefull in similar cases: [Flags]
public enum MyEnum
{
//meta values
typeThatShouldNotDoStuff = 1,
//real values
typeA = 2,
typeB = 4 | typeThatShouldNotDoStuff,
typeC = 8 | typeThatShouldNotDoStuff,
typeD = 16 | typeThatShouldNotDoStuff
}
var type = MyEnum.typeA;
if(!type.HasFlag(MyEnum.typeThatShouldNotDoStuff))
{
// do stuff
} It will look much nicer once you assign good semantic names to enum values. |
Beta Was this translation helpful? Give feedback.
-
with if(type is not (MyEnum.typeB or MyEnum.typeC or MyEnum.typeD))
{
// do stuff
}
if(foo is "some" or "random" or "value" or "bar")
{
// do stuff
}
const int limitA = 5;
const int limitB = 10;
var foo = 15;
if(foo is > limitA and > limitB)
{
// do stuff
} However it is limited to only work on constants. |
Beta Was this translation helpful? Give feedback.
-
I use a |
Beta Was this translation helpful? Give feedback.
with
and
,or
,not
,>
and<
patterns, this is all possible in C# 9:However it is limited to only work on constants.