Do else if statements exist in C#?

前端 未结 8 1565
感动是毒
感动是毒 2021-02-01 12:51

I have come across the following code in C#.

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


        
相关标签:
8条回答
  • 2021-02-01 13:12

    There is no "else if" statement in C#.

    For that matter, I don't know that there are any multi-word statement keywords in C#.

    0 讨论(0)
  • 2021-02-01 13:21

    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.

    0 讨论(0)
  • 2021-02-01 13:27

    The construct else if is never mentioned in the C# specification, except in some examples where it is used without explanation. So I do not think it is a special construct, it is just nested if statements.

    0 讨论(0)
  • 2021-02-01 13:30

    The two examples you give are equivalent in every language. In C or C#, it's exactly equivalent to an else, then if. In some other languages, elseif is syntactic sugar for else, then if. So no matter which language you use, they will compile to the same code (or be interpreted to the same behavior). See http://en.wikipedia.org/wiki/Conditional_%28programming%29#Else_If

    0 讨论(0)
  • 2021-02-01 13:33

    The Selection Statement of the C# Language Specification only shows if and switch statements. If you select the if statement, it says:

    The if statement selects a statement for execution based on the value of a Boolean expression.

    if-statement:

    if ( boolean-expression ) embedded-statement

    if ( boolean-expression ) embedded-statement else embedded-statement boolean-expression: expression

    An else part is associated with the lexically nearest preceding if that is allowed by the syntax

    0 讨论(0)
  • 2021-02-01 13:35

    You are correct. It's just an else followed by an if.

    0 讨论(0)
提交回复
热议问题