2

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

return if (condition)
jj_
  • 2,548
  • 28
  • 55
  • 2
    No, but `if (condition) return;` is the same length. – Lee Mar 10 '16 at 10:52
  • what about `return (condition) ? "this value if condition is true" : "this one if condition is false"`? – Nitro.de Mar 10 '16 at 10:56
  • 1
    @Nitro.de This is about conditionally returning, not about returning different values depending on a condition. – James Thorpe Mar 10 '16 at 10:57
  • @Lee Not about length, but readability / expressiveness. `return if (condition)` makes it clear since the first word that this line is for returning. – jj_ Mar 10 '16 at 11:12

1 Answers1

5

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;
Ondrej Tucny
  • 26,009
  • 6
  • 63
  • 87