Ternary Operator in C#

Have you ever play any game which is based on any condition for example let’s suppose that you are playing an interesting game with your friend and if you win the game then you will get treat from your friend and in case you loss that game you will also loss the opportunity to have pizza and chocolate late .I just gave you a real world example Now let’s talk in term of programming there are so many situations arises in a single project that you have to make decisions based upon various conditions and hence the concept of ternary operator comes in existence . It is denoted by a question mark ‘?’ and sometime called conditional operator.

Basic Syntax:

    Condition ? ‘‘TRUE’:’FALSE ’

It is quite clear but let’s take the help of words to make it more understandable that if the condition will be true or satisfied then this statement will return true else it will return false.


If the cricket team scores more than 540 then it will win the match otherwise it will be unable to take the trophy:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  7. namespace TernaryOperator  
  8. {  
  10.     class ternary {  
  11.         public int score;  
  13.         public ternary(int s)  
  14.         {  
  15.             score = s;  
  16.         }  
  17.     }  
  20.     class Program  
  21.     {  
  22.         static void Main(string[] args)  
  23.         {  
  25.             ternary team = new ternary(580);  
  26.             Console.WriteLine(team.score > 540 ? "Won":"Lost");  
  27.             Console.ReadKey();  
  28.         }  
  29.     }  
  30. }  



Next Recommended Reading Use Ternary Operator In C# Language