Inline If Statement

Ok, so here is a simple example of how to use an inline if statement. In an inline if statement, the conditions are just in one line of code. You don’t have to do as much declaration and code as in a normal if statement. To do these inline if statements, you have to use the conditional operator (?:).

In the example we are checking which variable is the largest. If the value of variable ‘a’ is larger than the value of variable ‘b’, we assign the text “a is larger than b” to the string ‘result’. Otherwise, we assign the text “b is larger than a“.

Syntax
variable = ( condition ? true value : false value )

Original way

int a = 1;
int b = 5;
string result = string.Empty;

if (a > b)
{
result  = "a is larger than b";
}
else
{
result  = "b is larger than a";
}

Inline way

string result  = ( a > b ? "a is larger than b" : "b is larger than a");
Advertisements

Comments are closed.

%d bloggers like this: