If and Else-If clauses
This article is about if and else-if statements in CSharp. If is used very often during programming. Any time you want to do something only if a certain condition is met. The easiest way to understand If and Else If is to use an example:
Syntax for If and Else If statements
int age=15; // German law applies ;) if(age<16){ Console.WriteLine("No alcohol for you!"); }else if(age==16){ Console.WriteLine("Only beer and wine my friend"); }else if(age==17){ Console.WriteLine("You cant enter!"); }else{ Console.WriteLine("Do as you please"); }
Here, we have to consider three different terms in CSharp. If – as first and imperative – also has the highest priority, because only if this condition is not met, else if is queried. Else if – as 2nd to n-th query – only necessary if you have other conditions. Else – last and only necessary if you want to have a “remainder” case – this case is invoked if the if and else if cases have not occurred. If we want to, we can also do two if queries one behind the other. E.g.
Example for If and Else-If queries in CSharp
string motivation = "high"; string intelligence = "low"; if (intelligence== "low") { Console.WriteLine("dumb"); } if (motivation == "high") { Console.WriteLine("great"); } else { Console.WriteLine("so so"); } Console.Read();
In this case both, dumb and great are written to the console. If use the following on the other hand…:
string motivation = "high"; string intelligence = "low"; if (intelligence == "low"){ Console.WriteLine"dumb"); }else if (motivation == "high"){ Console.WriteLine("great"); }else{ Console.WriteLine("so so"); }
… else if instead if just if in the second statement, only “dumb” is being written to the console.
As you can see you already have many ways of using if and else if in order to write applications which can take decisions.