In this article, We will discuss about When to Use If Else and When to Use Switch Statement in C#.
Well it depends upon the Situation that When to Use If Else and When to Use Switch.
Suppose if we have One or two Condition then it is better to Use If Else but if we have more than two Conditions then at that time it is better to Use Switch Case.
Whenever We Use Switch Case Statement, then at the Compile time it Creates a lookup table Which Contains all the Cases and While running the Program it directly Check that Case in lookup table, if Satisfied then directly execute that Case.
Example 1:-
------------------
In this example we want to Check the value of i=1 or i=2 then in this case We can use If Else.
If(i==1)
{
//rest of code
}
else
{
//rest of code
}
Here no need to use Switch Case because we don't have much Condition.
Example 2:-
------------------
In this example we want to Check the value of i=70 then in this case We can use Switch.
Switch(i)
{
Case 1:
Case 2:
.
.
.
Case 70:
}
Here When the Value of i=70 then directly Case 70 Will hit Without Checking Previous 69 Condition but if we apply the same thing in if else then after checking 69th conditions then 70th Condition will hit and Which is really a waste of time and performance.
So finally, Based on the Conditions We need to use If Else vs Switch Condition.
0 comments:
Post a Comment