peter peter - 4 years ago 97
C# Question

C# else if confusion

I am currently studying the conditional constructions. Correct me if I am wrong but else if and else(if(){}) is the same thing... Example:

a=5;
if(a==6)
{
Console.WriteLine("Variable 'a' is 6");
}
else if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}


And

a=5;
if(a==6)
{
Console.WriteLine("Variable 'a' is 6");
}
else
{
if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}
}


Are these things the same? And if yes why does else if exist if I can write it the "second way"(the second example that I wrote)?

Tim Tim
Answer Source

Yes, these are effectively identical.

The reason the "else if" statement exists is to make cleaner code when there are many conditions to test for. For example:

if (a==b) {
   //blah
} else if (a==c) {
   //blah
} else if (a==d) {
   //blah
} else if (a==e) {
   //blah
}

is much cleaner than the nested approach

if (a==b) { 
    //blah
} else {    
    if (a==c) {
        //blah
    } else {
        if (a==d) {
            //blah
        } else {
            if (a==e) {
                //blah
            }
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download