C# If
Array Class Collections File String .NET Algorithm ASP.NETCast Compression Data Delegate Directive Enum Exception IfInterface Keyword LINQ Loop Method Number Regex SortStringBuilder Struct Switch Time Value Windows WPF
Often a value is not known. With an if-statement, we make a logical decision based on it. In an if-statement, we test expressions. These evaluate to true or false. And logical operators chain expressions.
A value can be tested by either an if-statement or a switch statement.Stroustrup, p. 133
Example
This program computes the value of an expression. It then tests it in an if-statement. The condition inside the if-statement is evaluated to a boolean value. If the value is true, the inner block is executed.
True:The value equals 5 and thus the expression evaluates to true. The Console.WriteLine method is called.
True, False
Info:In a compiled language, an optimizer can evaluate constants like these even before they are run.
Program that uses if-statement: C# using System; class Program { static void Main() { int value = 10 / 2; if (value == 5) { Console.WriteLine(true); } } } Output True
Else if
Next, we introduce the "else" statements. The Test method uses the if-statement with two else-if blocks and one else. It returns a value based on the formal parameter. The order of the if-statement tests is important.
So:We must test the more restrictive conditions first, or the less restrictive ones will match both cases.
Program that uses if, else: C# using System; class Program { static void Main() { // Call method with embedded if-statement three times. int result1 = Test(0); int result2 = Test(50); int result3 = Test(-1); // Print results. Console.WriteLine(result1); Console.WriteLine(result2); Console.WriteLine(result3); } static int Test(int value) { if (value == 0) { return -1; } else if (value <= 10) { return 0; } else if (value <= 100) { return 1; } else // See note on "else after return" { return 2; } } } Output -1 1 0
In this program, the Test method uses several branching instructions expressed in high-level if-statements. The formal parameter is tested against zero. We then see if it is less than or equal to ten, and next, 100.
Static Method
Else return. Test() uses a four-part if-statement. It has an else-clause that returns a value. All of the blocks in the if-statement return a value. This means there is no reachable point in the method after the else-statement.
Return
Tip:You could delete the else-statement and put the "return 2" code on a separate line.
Else
Note:This reduces the symmetry of the code.
But it also makes it shorter.
It has less syntax noise.
But it also makes it shorter.
It has less syntax noise.
Expressions
The expression in an if-statement must evaluate to true or false. A number result, or a reference type, is not accepted—a compiler error will occur. Expressions can be complex. Here we see how an expression can be written in two ways.
Tip:In this program, try changing the values of A and B to 1 and 2. With those values, the if-expressions both evaluate to false.
Program that uses if, expressions: C# using System; class Program { static void Main() { int a = 1; int b = 3; // Use negated expression. if (!(a == 1 && b == 2)) { Console.WriteLine(true); } // Use binary or version. if (a != 1 || b != 2) { Console.WriteLine(true); } } } Output True True
Brackets
Brackets are not always required in C# programs. In this example, we use no curly brackets. The bodies of the if-statements are simply the following statements in the source. And if-statements can be nested this way.
Caution:This style is often a bad idea. You cannot add a second line to the body of one of these if-statements.
And:Visual Studio will now insert brackets automatically, so this style of code is not even faster to develop.
The final part of this example, which is a single-line if-statement, may be most useful. If you use a single-line if-statement, the chances a further change will cause problems are less. The code may seem more logical when read.
Program that uses no brackets: C# using System; class Program { static void Main() { int value = 1; int size = 2; if (value == 1) if (size == 2) Console.WriteLine("1, 2"); if (value == 0) Console.WriteLine("0"); // Not reached. else Console.WriteLine("Not 0"); // Reached. if (value == 2) Console.WriteLine("2"); // Not reached. } } Output 1, 2 Not 0
Nested ifs
Nesting if-statements will create a similar flow of control to using the boolean && operator. The arrangement of your if-statements will impact performance in some situations. We explore nested ifs.
Nested IfSwitch
The C# language provides a switch construct that in many cases will provide better performance than if-statements. The compiler turns integer or enum switch statements into jump tables and string switches into Dictionary instances.
Caution:Switch statements can only test an expression against constant values. This is their main limitation.
SwitchTernary
What is the ternary operator? It is like a question with two answers. It allows us to express a predicate and two consequent statements inside one statement. The ternary statement is compiled into the same code as if-statements use.
Ternary Operator
Null coalescing:This operator uses two question marks. Similar to ternary, it can only be used on a reference variable.
Null Coalescing OperatorPerformance
In a complex program, having many if-statements for rare paths will reduce performance for common paths. This problem can be solved by using a lookup table or Dictionary. We can encode the branches in data objects.
1. Change expression order.It is possible to improve the performance of if-statements by changing the order you test conditions.
Short-Circuit
2. Use switch.In some program contexts a switch statement is faster than an if-statement. But this is a complex issue.
If Versus Switch Performance
3. Reorder statements.Another way to optimize if-statements is to simply test some conditions before others.
Reorder If-Statements
4. Use Dictionary.A Dictionary can be used as a lookup table. This transforms complex if-statements into a single lookup.
Dictionary
5. Virtual dispatch:Use the type system to add behavior to objects. Place objects in a Dictionary and call their virtual methods.
VirtualIL
We consider how if-statements are translated into machine code, which is preceded by intermediate language in the .NET Framework. High-level languages provide structured models. Blocks of code are separated with parentheses.
However, these blocks are meaningless to the execution engine. They are instead translated into single instructions that are part of the intermediate language. The IL is flat. It is without scope.
Thus:If-statements are translated to branch instructions. If the condition matches, these "jump" forward.
bne InstructionIntermediate LanguagePaths
If-statements can be used poorly. If your code has a normal, expected path, try not to obscure that path with excessive if-statements. Instead, use ifs for branches from that path. Next we see what Code Complete has to say.
Write your code so that the normal path through the code is clear. Make sure that the rare cases don't obscure the normal path of execution. This is important for both readability and performance.McConnell, p. 355
If two paths are possible, it is often better to put the common one in the if, and the uncommon one in the else. When reading the code, the more important (common) paths should come first. Earlier things are perceived as more important.
Tip:Some understanding of psychology helps when coding. Clear if-statements make code easier to understand.
Summary
Control flow is like a river. As it proceeds, if-statements cause branches in its path. We find branch opcodes are used in the low-level representation of code. With these, the river forks into separate streams.
Provided :
http://www.tutorialspoint.com/csharp/if_else_statement_in_csharp.htm