Understanding C#'s "If" Statement

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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com