This code snippet is a great example of using if and else statements in C# and will provide any beginning programmer the necessary knowledge to begin evaluating boolean expressions. For all code snippets make sure they are in a class and contain a main statement or else they will not run, also make sure to use the correct "using" statements!
using System;
namespace Branching
{
public class TestIfElse
{
static void Main()
{
int valueOne = 10;
int valueTwo = 20;
Console.WriteLine("Testing valueOne against valueTwo...");
if ( valueOne > valueTwo )
{
Console.WriteLine(
"ValueOne: {0} larger than ValueTwo: {1}",
valueOne, valueTwo);
} // end if
else
{
Console.WriteLine(
"Nope, ValueOne: {0} is NOT larger than ValueTwo: {1}",
valueOne, valueTwo);
} // end else
} // end Main
} // end class
} // end namespace
In this code, the if( valueOne > valueTwo) is evaluating whether valueOne (10) is greater than valueTwo (20). If that statement evaluates to true (which it won't) then the code in the brackets will be executed. If it evaluates to false (which it will) then the code in the else statement will evaluate. In addition to if and else, the "if else" statement can be used which is placed after the first if statement and is also checked before reaching the else statement. This could be useful if, for example, you wanted to test if (valueOne == valueTwo) in which case you would print out a line that these two values are equal.
Article Source: http://EzineArticles.com/3772305