The ternary operator, also known as the conditional operator, is a shorthand way of writing an if-else statement.
It allows you to write concise conditional expressions in a single line of code.
The syntax of the ternary operator in C# is as follows:
condition ? expression1 : expression2;
If the condition is true, expression1 becomes the result of the entire expression. If the condition is false, expression2 becomes the result.
Here are a few examples to illustrate the usage of the ternary operator in C#:
int number = 10;
string result = number % 2 == 0 ? "Even" : "Odd";
Console.WriteLine(result);
In this example, we use the ternary operator to determine whether number
is even or odd. If number % 2 == 0
is true, the expression "Even"
is assigned to the variable result
.
Otherwise, the expression "Odd"
is assigned. In this case, since number
is 10 and divisible by 2, the output will be “Even”.
int age = 25;
string message = age >= 18 ? "You are an adult" : "You are a minor";
Console.WriteLine(message);
In this example, we use the ternary operator to check if age
is greater than or equal to 18. If it is true, the expression "You are an adult"
is assigned to message
.
Otherwise, the expression "You are a minor"
is assigned. Since age
is 25, which is greater than 18, the output will be “You are an adult”.
Practical Uses
The ternary operator in has several practical use cases. Such as follows:
Assigning Values Based on Conditions
One common use of the ternary operator is to assign a value to a variable based on a condition.
int age = 25;
string status = age >= 18 ? "Adult" : "Minor";
In this example, if the age
is greater than or equal to 18, the value “Adult” is assigned to the status
variable. Otherwise, the value “Minor” is assigned.
Inline Conditional Rendering
In UI frameworks like ASP.NET, the ternary operator can be used for inline conditional rendering, making templates cleaner.
<span>@(isAdmin ? "Admin Dashboard" : "User Dashboard")</span>
In this example, if the isAdmin
variable is true, the text “Admin Dashboard” will be rendered. Otherwise, the text “User Dashboard” will be displayed instead.
Setting Default Values
The ternary operator can be used to assign a default value to a variable if a particular condition is false.
string username = string.IsNullOrEmpty(input) ? "Guest" : input;
In this example, if the input
string is null or empty, the value “Guest” is assigned to the username
variable. Otherwise, the value of input
is assigned.
It can be a useful tool for writing concise and readable code when you have simple conditional expressions.
I found just what I needed. You have ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye
I’m glad you find it useful!
It is actually a great and useful piece of information. I am
satisfied that you simply shared this helpful info with us.
Please stay us informed like this. Thanks for sharing.