c sharp

What is ?: Operator in C#

The operator (?:) in C# is a conditional operator that can be used for if-else statements as It allows users to write more concise code that is easier to understand. The operator evaluates a Boolean expression and returns one of two possible values depending on whether the expression is true or false. This article will explore the ?: operator in detail and provide an example that uses it to illustrate the working of this operator.

What is ?: Operator in C#

The ?: operator, also known as the conditional operator, provides method of writing an if-else statement in C#. It takes three operands: a Boolean expression, and two expressions that are evaluated based on the Boolean result. The syntax is as follows:

condition ? <expression-to-be-evaluated 1> : <expression-to-be-evaluated 2>;

If the condition gets true, then expression1 will be evaluated and returned whereas if the condition is false, then expression2 will be evaluated and returned. The ?: operator is frequently used to simplify code and make it more readable.

How to Use the Ternary Operator ?: Operator in C#

To demonstrate the use of this ?: operator in C# below an example code i given that checks if the number entered is odd or even using the same operator:

using System;

class Program {

 static void Main(string[] args) {

  int num = 9;

  string result = (num % 2 == 0) ? "Number is even" : "Number is odd";

  Console.WriteLine(result);

 }

}

In this example, we declare an integer variable named num and assign it the value of 9 and next the ternary operator is used for checking if the number is odd or even.

The (num % 2 == 0) checks if the remainder of the variable “num” divided by 2 is equal to zero. In other words, it checks if “num” is an even number. The “%” symbol is called the modulus operator as it returns the remainder in the result of division and if the remainder is zero, it means the number is evenly divisible by 2 which means that it’s an even number.

If the number is even, the true_expression “Number is even” is returned and assigned to the string variable message.

Otherwise, the false_expression “Number is odd” is returned and assigned to the message variable. Finally, we print out the value of the message variable, which will be “Number is odd” since 9 is an odd number:

Conclusion

The ternary operator (?:) in C# is a useful shortcut for writing if-else statements. It allows us to write more readable code which in turn makes it easy for others to understand it, especially when dealing with simple conditional statements. However, it is important to use the operator carefully and only in cases where it improves code readability and maintainability.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.