If Statement

Why Trust Techopedia

What Does If Statement Mean?

An if statement, in C#, is a programming construct in C# used to selectively execute code statements based on the result of evaluating a Boolean expression. The Boolean expression must return either a true or false value.

Advertisements

The if statement is used as a control statement to branch to different sections of code depending on the result of the Boolean conditional expression. The expression is stated within parentheses and evaluated during execution. If the expression results in a true value, the code following the if statement is executed. Otherwise, the code following an optional “else” statement is executed. If there is no else statement, execution continues with the code after the if block.

The if statement provides a decision-making capability by which one piece of code is executed instead of the other based on one or more specified conditions.

Techopedia Explains If Statement

Multiple conditions can be combined in the Boolean expression to be evaluated within the if statement by using the OR operator (||) and/or the AND operator (&&). The other set of corresponding logical operators are | and &. The logical operators && and || produce more efficient code than the other regular ones because the entire expression does not always need to be evaluated. As a result, they are called short-circuit operators.

For example, an if statement can be used to check if a character input to the program is an alphabetical, numeric, or special character.

In contrast to languages like C or C++, where a result of zero is considered to be a false value and a number other than zero is considered to be true, C# expects results as Boolean values (true or false) only. Hence, for numeric conditions such as variable not equal to zero, the expression has to be explicitly written for that condition and not just evaluated with the number itself placed within parentheses.

Although the switch construct forms an alternative to the if statement and can provide better performance and clearer code, it can only be used to test expressions against constant values. The if statement can be replaced with a ternary operator when a condition is evaluated. The result of the evaluation is considered for assigning a variable to a value.

Advertisements

Related Terms

Margaret Rouse
Technology expert
Margaret Rouse
Technology expert

Margaret is an award-winning writer and educator known for her ability to explain complex technical topics to a non-technical business audience. Over the past twenty years, her IT definitions have been published by Que in an encyclopedia of technology terms and cited in articles in the New York Times, Time Magazine, USA Today, ZDNet, PC Magazine, and Discovery Magazine. She joined Techopedia in 2011. Margaret’s idea of ​​a fun day is to help IT and business professionals to learn to speak each other’s highly specialized languages.