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:
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.
Example:
If the cricket team scores more than 540 then it will win the match otherwise it will be unable to take the trophy:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace TernaryOperator
- {
-
- class ternary {
- public int score;
-
- public ternary(int s)
- {
- score = s;
- }
- }
-
-
- class Program
- {
- static void Main(string[] args)
- {
-
- ternary team = new ternary(580);
- Console.WriteLine(team.score > 540 ? "Won":"Lost");
- Console.ReadKey();
- }
- }
- }
Output