Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# else if confusion

Tags:

c#

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)?

like image 417
peter Avatar asked Jan 24 '26 16:01

peter


1 Answers

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
            }
        }
    }
}
like image 190
Tim Avatar answered Jan 27 '26 06:01

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!