Does c# have a shorthand "something if (condition);" statement?

190 Views Asked by At

Simple and short: does C# have a shorthand if statement similar to Ruby's?

return if (condition)
1

There are 1 best solutions below

2
Ondrej Tucny On BEST ANSWER

No, it doesn't. The standard way is exactly the same length, so no such shorthand would be justified probably. Consider the usual syntax:

if (condition) return;

vs. a hypothetical:

return if (condition);

A possible reason for introducting such a 'reverse' syntax would be that the primary intent were expressed first. Because of left-to-right reading, then it would be easier to understand, leading to more readable code.


From a language design perspective, it would make sense using a different keyword such as when in order to prevent confusing bugs. Consider the following two lines of code:

return            // missing ; here
if (condition);   // no warning (except empty 'then' part)

should probably have been written as:

return;           // ; here present
if (condition);   // unreachable code warning here

From a character-saving perspective, it makes sense in begin … end language. A construct like this:

if condition begin
    return;
    end if;

would be significantly shorter and probably more readable if written as:

return when condition;