“else if()” versus multiple “if()”s in C#

后端 未结 10 2040
一个人的身影
一个人的身影 2021-01-03 21:51

How do these practically differ?

// Approach one
if (x == 1)
    DoSomething();
else if (x == 2)
    DoSomethingElse();

// Approach two
if (x == 1)
    DoSo         


        
10条回答
  •  死守一世寂寞
    2021-01-03 22:39

    When you code like this

    // approach two
    if (x == 1)
        DoSomething();
    if (x == 2)
        DoSomethingElse();
    

    Everytime the condition checks.

    But when you code like this

    if (x == 1)
        DoSomething();
    else if (x == 2)
        DoSomethingElse();
    

    If the first condition is true then it wont check next else if condition and thus decrease unnecessary compiling.

提交回复
热议问题