开发者

Is there a more terse way of writing if-statements in C#?

开发者 https://www.devze.com 2023-02-06 21:07 出处:网络
Perhaps there is and I don\'t know about it and if so I would gladly like to be enlightened. I would like to be able to using something similar to the ?: operator but without having to include the : a

Perhaps there is and I don't know about it and if so I would gladly like to be enlightened. I would like to be able to using something similar to the ?: operator but without having to include the : and without having to assign the result to a variable, like so:

q?r();

which would be semantically identically to

if (q)
{
    r();
}

Edit: I should've expressed myself clearer. I'm looking for a way to get rid of the if's and e开发者_开发知识库lse's and express the conditional statement with a more functional style.

Cheers, /Christian


if (q) r();

That's about as terse as you can get with it.


Sometimes you can save writing if statements by using LINQ.

For example, instead of:

int CountItemsLargerThanFive(IEnumerable<int> collection)
{
   int count = 0;
   foreach (var item in collection)
   {
      if (item > 5)
      {
         count++;
      }
   }
   return count;
}

You can write:

int CountItemsLargerThanFive(IEnumerable<int> collection)
{
   return collection.Count(item => item > 5);
}

No if's!

And there are many other cases in which control structures such as if can be replaced by LINQ.


If you want to execute a single statement, you can omit the brackets and write it on a single line:

if (q) r();

Normally it's more readable to have the condition and the code on separate lines, and always include the brackets, but if both the condition and the code are simple, the readability should not be a problem.

Example:

if (line > 0) builder.AppendLine();

as an alternative to:

if (line > 0) {
  builder.AppendLine();
}


As others have mentioned, stick with the obvious route.

For fun, here's a way to use the conditional operator like you'd wanted, with delegates (please don't do this):

(q ? (Action)r : () => { })();

which looks slightly nicer if there were a genuine else:

(q ? (Action)trueAction : falseAction)();


you can also use : x ?? 0 this is the null checking

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号