Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
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 6:30am

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.
 
Share this answer
 
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.
 
Share this answer
 
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.
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[^]
 
Share this answer
 
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
}
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900