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 é uma premiada redatora e professora conhecida por sua habilidade de explicar assuntos técnicos complexos para um público empresarial não técnico. Nos últimos vinte anos, suas definições de TI foram publicadas pela Que em uma enciclopédia de termos tecnológicos e citadas em artigos do New York Times, Time Magazine, USA Today, ZDNet, PC Magazine e Discovery Magazine. Ela ingressou na Techopedia em 2011. A ideia de Margaret de um dia divertido é ajudar os profissionais de TI e de negócios a aprenderem a falar os idiomas altamente especializados uns dos outros.