1
+ using System ;
2
+
3
+ class TernaryOperatorDemo
4
+ {
5
+ static void Main ( )
6
+ {
7
+ // Basic usage of ternary operator
8
+ int a = 10 ;
9
+ int b = 20 ;
10
+ string result = a > b ? "a is greater than b" : "a is not greater than b" ;
11
+ Console . WriteLine ( result ) ;
12
+
13
+ // Nested ternary operator
14
+ int score = 85 ;
15
+ string grade = score >= 90 ? "A" :
16
+ score >= 80 ? "B" :
17
+ score >= 70 ? "C" :
18
+ score >= 60 ? "D" : "F" ;
19
+ Console . WriteLine ( $ "The grade is: { grade } ") ;
20
+
21
+ // Ternary operator with different data types
22
+ bool isAdult = true ;
23
+ string message = isAdult ? "You are an adult." : "You are not an adult." ;
24
+ Console . WriteLine ( message ) ;
25
+
26
+ // Assigning the result to a variable
27
+ int x = 5 ;
28
+ int y = 10 ;
29
+ int max = x > y ? x : y ;
30
+ Console . WriteLine ( $ "The maximum value is: { max } ") ;
31
+
32
+ // Inline use in Console.WriteLine
33
+ int age = 25 ;
34
+ Console . WriteLine ( age >= 18 ? "You can vote." : "You cannot vote." ) ;
35
+
36
+ // Method returning a value based on ternary operator
37
+ Console . WriteLine ( CheckEvenOdd ( 10 ) ) ; // Output: Even
38
+ Console . WriteLine ( CheckEvenOdd ( 7 ) ) ; // Output: Odd
39
+
40
+ // Ternary operator used as method parameter
41
+ bool isHappy = true ;
42
+ PrintMessage ( isHappy ? "I'm happy!" : "I'm not happy." ) ;
43
+
44
+ // Ternary operator in a complex expression
45
+ int c = 15 ;
46
+ max = ( a > b ? a : b ) > c ? ( a > b ? a : b ) : c ;
47
+ Console . WriteLine ( $ "The maximum value is: { max } ") ;
48
+ }
49
+
50
+ // Method returning a value based on ternary operator
51
+ static string CheckEvenOdd ( int number )
52
+ {
53
+ return number % 2 == 0 ? "Even" : "Odd" ;
54
+ }
55
+
56
+
57
+ static void PrintMessage ( string message )
58
+ {
59
+ Console . WriteLine ( message ) ;
60
+ }
61
+ }
0 commit comments