if if...else if... else if

suggest change

The if statement is used to control the flow of the program. An if statement identifies which statement to run based on the value of a Boolean expression.

For a single statement, the braces are optional but recommended.

int a = 4;
if(a % 2 == 0) 
{
     Console.WriteLine("a contains an even number");
}
// output: "a contains an even number"

The if can also have an else clause, that will be executed in case the condition evaluates to false:

int a = 5;
if(a % 2 == 0) 
{
     Console.WriteLine("a contains an even number");
}
else
{
     Console.WriteLine("a contains an odd number");
}
// output: "a contains an odd number"

The ifelse if construct lets you specify multiple conditions:

int a = 9;
if(a % 2 == 0) 
{
     Console.WriteLine("a contains an even number");
}
else if(a % 3 == 0) 
{
     Console.WriteLine("a contains an odd number that is a multiple of 3"); 
}
else
{
     Console.WriteLine("a contains an odd number");
}
// output: "a contains an odd number that is a multiple of 3"

Important to note: if a condition is met in the above example , the control skips other tests and jumps to the end of that particular if else construct.So, the order of tests is important if you are using if .. else if construct

C# Boolean expressions use short-circuit evaluation. This is important in cases where evaluating conditions may have side effects:

if (someBooleanMethodWithSideEffects() && someOtherBooleanMethodWithSideEffects()) {
  //...
}

There’s no guarantee that someOtherBooleanMethodWithSideEffects will actually run.

It’s also important in cases where earlier conditions ensure that it’s “safe” to evaluate later ones. For example:

if (someCollection != null && someCollection.Count > 0) {
   // ..
}

The order is very important in this case because, if we reverse the order:

if (someCollection.Count > 0 && someCollection != null) {

it will throw a NullReferenceException if someCollection is null.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Keywords:
* as
* goto
* break
* const
* for
* is
* fixed
* sealed
* typeof
* this
* void
* char
* params
* base
* string
* null
* return
* while
* using
* ulong
* uint
* unsafe
* int
* var
* lock
* where
* extern
* switch
* when
* struct
* static
* if if...else if... else if
* do
* bool
* long
* sizeof
* in
* enum
* ushort
* sbyte
* event

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
51 Keywords
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script