Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do else if statements exist in C#?

I have come across the following code in C#.

if(condition0) statement0; else if(condition1) statement1; else if(condition2) statement2; else if(condition3) statement3; ... else if(conditionN) statementN; else lastStatement; 

Some of my colleagues tell me that this is an else if statement. However, I am convinced that it is actually a multi-layered nested if-else statement. I know that without delimiters {}, one statement is allowed in an if or else. So in this case I think it would be equivalent to the following code.

if(condition0)    statement0; else   if(condition1)     statement1;   else     if(condition2)       statement2;     else       if(condition3)         statement3;       else       ... 

Note that all I changed was the whitespace. This indentation works because each else goes back to the most recent if statement when there are no delimiters.

Can anyone clarify if the else if format in the first example is treated differently by the compiler than the nested if-else format in the second example?

like image 810
Aviv B. Avatar asked Jul 30 '10 19:07

Aviv B.


People also ask

Does C use Elif or else if?

In the C Programming Language, the #elif provides an alternate action when used with the #if, #ifdef, or #ifndef directives.

Does every If statement need an else in C?

No, It's not required to write the else part for the if statement.

What is else if clause in C?

In an if...else statement, if the code in the parenthesis of the if statement is true, the code inside its brackets is executed. But if the statement inside the parenthesis is false, all the code within the else statement's brackets is executed instead. Output: Statement is False!

How many else if can I use in C?

There can be any number of else..if statement in a if else..if block. 4. If none of the conditions are met then the statements in else block gets executed.


2 Answers

You are correct; there is no such thing as an "else if" statement in C#. It's just an else where the statement of the alternative clause is itself an if statement.

Of course, the IDE treats "else if" as special so that you get the nice formatting you'd expect.

Note that there is an #elif construct in the "preprocessor" syntax.

Note also that C, C++ and ECMAScript - and I am sure many more C-like languages - also have the property that there is no formal "else if" statement. Rather, in each the behaviour falls out of the definition of "else" as coming before a single statement.

like image 186
Eric Lippert Avatar answered Sep 25 '22 09:09

Eric Lippert


It's a multi-layered if-else.

The reason it is has to do with c# syntax rules. An else is followed by a statement, and any if chain qualifies as a statement.

like image 31
Robert Harvey Avatar answered Sep 26 '22 09:09

Robert Harvey