The if Statement c#
The if statement is a far more versatile and useful way to make decisions. Unlike ?: statements, if statements don ’ t have a result (so you can ’ t use them in assignments); instead, you use the statement to conditionally execute other statements. The simplest use of an if statement is as follows, where < test > is evaluated (it must evaluate to a Boolean value for the code to compile) and the line of code that follows the statement is executed if
< test > evaluates to true :
if ( < test > )
< code executed if < test > is true > ;
After this code is executed, or if it isn ’ t executed due to < test > evaluating to false , program execution resumes at the next line of code.
You can also specify additional code using the else statement in combination with an if statement. This statement is executed if < test > evaluates to false :
if ( < test > )
< code executed if < test > is true > ;
else
< code executed if < test > is false > ;
Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string comparison; Console.WriteLine("Enter a number:"); double var1 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter another number:"); double var2 = Convert.ToDouble(Console.ReadLine()); if (var1 < var2) comparison = "less than"; else { if (var1 == var2) comparison = "equal to"; else comparison = "greater than"; } Console.WriteLine("The first number is {0} the second number.", comparison); Console.ReadKey(); } } }