Here is a simple example of how to utilize an inline if statement in your C# code. One of the benefits in using inline if statements is less declaration of variables and less code and applying a condition in one line of code.
Here are two examples of the same if statement. The second one is using inline. In this example we are checking if variable “a” is equal to 5, if so assign “five” to variable “b” if not than assign “zero” to variable “b”.
Variable = (condition ? true value : false value )
Original way:
int a = 5;
string b = string.Empty;
if (a == 5)
{
b = "five";
}
else
{
b = "zero";
}
Inline way:
b = (a == 5 ? "five" : "zero");