How to Use the Conditional Operator (?) in C# ?

Conditional Operator is also called as ternary operator which lets the developers to select between 2 values with a statement.

Assume that you have to check for a number if it is even , we generally tend to use the if else statement . The same can be achieved using the ternary operator in C#.

How to Use the Conditional Operator (?) in C# ?

Below is a sample code snippet demonstrating the usage of the conditional or ternary operator in C# to find if the number is even.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ACSampleCode
{
    class Program
    {
        static void Main(string[] args)
        {
            int input = 4;
            bool evenNumber = input %2==0 ? true : false;
            Console.WriteLine(evenNumber);
            Console.ReadLine();
        }
    }

}
1