Click here to Skip to main content
14,360,161 members
Rate this:
Please Sign up or sign in to vote.
See more:
why microsoft has provided if else and switch case both.. what is fundamental difference between both?


What I have tried:

I have searched on google but not found fundamental difference between both.
Posted
Updated 8-Nov-19 7:30am
Rate this:
Please Sign up or sign in to vote.

Solution 3

That comes from the C programming language (so I'm writing with C perspective in mind).
There can be performance differences between (long chain of) if/else if/else statements and switch (the latter being faster) but, in my opinion, the syntax matters more:
The if/else if/else construct is more versatile (not limited to comparisons with constant values) an better suited when the count of the conditions is relatively small. On the other hand, the switch statement is more concise and better suited when you have to cover a relatively large number of cases.
   
Rate this:
Please Sign up or sign in to vote.

Solution 1

These are not really anything to do with Microsoft. They are fundamental parts of the programming languages going back to pre C-language days. Study the documentation to see where each is appropriate to use.
   
Comments
Vijay Radia 8-Nov-19 7:27am
   
i just want to know how c# compiler exactly compiles both
Richard MacCutchan 8-Nov-19 7:35am
   
There is not space here to explain the inner workings of a compiler. There are many examples and tutorials on the internet, that explain both statements.
Rate this:
Please Sign up or sign in to vote.

Solution 2

Sometimes a Switch can be faster than an If else construction, but this is not always the case. Besides this will only be important if the code is iterated or called hundreds of times.
See examples here: https://www.dotnetperls.com/if-switch-performance[^]
   
Rate this:
Please Sign up or sign in to vote.

Solution 4

Switch and if else are fundamentally different but both might replace each other in some cases. Switch evaluates a single expression and base on different results of the expression it selects different cases.
switch (i)
{
       case 1:
           Console.Write("1");
           break;
       case 2:
           Console.Write("2");
           break;
       default:
           Console.Write("default");
           break;
}

However, In case of if else, it eveluates multiple boolean expression and base of true or false , takes action
if(i>40)
{
   do something
}
else if(i>25 && i<35)
{
   do something
}
else if(i<20)
{
   do something
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100