Everyday Computing Advanced Computing The Internet At Home Health, Mind & Body Making & Managing Money Sports & Leisure Travel Beyond The Classroom
Certification
Databases
Networking
Programming
Moms, Dads, and Grads -- Win $500!
C# 2008 For Dummies

Understanding C#'s "If" Statement


Adapted From: C# 2008 For Dummies

The basis of all C# decision-making capability is the if statement, as follows:

if (bool-expression)
{
// Control goes here if the expression is true.
}
// Control passes to this statement whether the expression is true or not.

A pair of parentheses immediately following the keyword if contains some conditional expression of type bool. Immediately following the expression is a block of code set off by a pair of braces. If the expression is true, the program executes the code within the braces. If the expression is not true, the program skips the code in the braces. (If it does execute the code in braces, it ends up just after the closing brace and continues from there.)

The if statement is easier to understand with a concrete example:

// Make sure that a is not negative:
// If a is less than 0 . . .
if (a < 0)
{
// . . .then assign 0 to it so it won't be negative any longer.
a = 0;
}

This segment of code makes sure that the variable a is nonnegative — greater than or equal to 0. The if statement says, "If a is less than 0, assign 0 to a." (In other words, turn a into a positive value.)

The braces are not required. C# treats if(bool-expression) statement; as if it had been written if(bool-expression) {statement;}. The general consensus is to always use braces for better clarity. In other words, don't ask — just do it.

Related Articles
Getting a Handle on Computer Languages, C#, and .NET
Creating the Source Program for Your First C# Console Application
Examining the C# "Else" Statement
Visual Basic's Role in the Framework
Organizing Your Project with the Solution Explorer
Related Titles
RibbonX For Dummies
C# 2008 For Dummies
Microsoft SQL Server 2005 Reporting Services For Dummies
C# 2005 For Dummies
Oracle PL/SQL For Dummies