C# Ternary Operators
The operators used for decision making which replaces the conditional statements if and else are called a ternary operator in c#, which consists of three arguments among which the first argument is used for comparison and if the result of this comparison is true, the second argument is returned, it the result of the comparison is false, the third argument is returned, and this operator can be thought of as an optimized way of using if-else statement.
Syntax:
Boolean Expression ? First statement : Second statement
The above syntax represents the ternary operator. It consists of three parts. The first part of the syntax is before ?. It returns a Boolean value true or false because it is a conditional expression. The second part of the syntax is before ‘?’ and after ‘:’, which is executed if the result of the first part’s conditional expression is true. The third part of the syntax after the ‘:’ statement is executed if the result of the conditional expression that is the first part is false.
Working of C# Ternary Operators
Following are the different examples of ternary operators.
1. Comparison of Two Values Using If Else
Consider the below C# program for comparison of two values using the if-else statement.
Code:
using System; namespace Project { class MainClass { public static void Main(string[] args) { int a = 30; int b = 40; if (a < b) { Console.WriteLine("a's value is less than b"); } else { Console.WriteLine("b's value is less than a"); } } } }
Output:
In the above program, two variables, a and b, are defined and assigned some values. Their values are compared against each other to find out which is greater using if-else conditional statements. The above program consists of twenty lines of code to compare two values against each other. The same code can be optimized to fourteen lines by using the ternary operator, which is used in the code below:
2. Comparison of Two Values Using Ternary Operators
Consider the below C# program for comparison of two values using ternary operators.
Code:
using System; namespace Project { class MainClass { public static void Main(string[] args) { int a = 40; int b = 30; Console.WriteLine((a < b) ? "a's value is more than b" : "b's value is less than a"); } } }
Output:
In the above program, two variables, a and b, are defined and assigned some values. Their values are compared against each other to find out which is greater using ternary operators. The conditional statement is executed, and the result of the statement is assigned to a variable res. If the conditional statement’s result is true, the second statement after the ‘?’, which is a’s value is more than b, is printed; otherwise, the third statement after the ‘:’ b’s value is less than a is printed.
3. Nested Ternary Operator
When the second argument or the third argument after ‘?’ or after ‘:’ is a conditional statement again, then the operator is called the nested ternary operator. Consider the below program, for example:
Code:
using System; namespace Project { public class MainClass { public static void Main(string[] args) { int a = 10; int b = 8; Console.WriteLine(a> b ? "a's value is more than b" : a < b ? "a's value is less than b" : a == b ? "C" : "No result"); } } }
Output:
In the above program, two variables, a and b, are defined and assigned some values. Their values are compared against each other to find out which is greater or if they are equal using ternary operators in C#. The conditional statement is executed, and the result of the statement is assigned to a variable res. If the result of the conditional statement is true, the second statement after the ‘?’ which is again a conditional statement a
Note: Ternary operators cannot execute statements. It only returns an expression or value present in the second part or third part depending on the conditional statement’s result in the first part.
Examples of C# Ternary Operators
Following are the different examples of ternary operators in C#.
Example #1
C# program using nested ternary operator to find out the largest of the given numbers.
Code:
using System; using System.IO; using System.Text; //Define Namespace namespace program { //Define class public class large { //Define main method public static void Main(string[] args) { //Define three variables to take the input int x; int y; int z; //Get the input from the users Console.Write("First number must be entered : "); x = Convert.ToInt32(Console.ReadLine()); Console.Write("Second number must be entered: "); y = Convert.ToInt32(Console.ReadLine()); Console.Write("Third number must be entered : "); z = Convert.ToInt32(Console.ReadLine()); //largest number is found out by using nested ternary operator int large = (x>y)?((x>z)?x:z):(y>z?y:z); //display the largest number Console.WriteLine("{0} is the largest number", large); Console.ReadLine(); } } }
Output:
Example #2
C# program using the ternary operator to find out if a given number is even or not.
Code:
using System; // Define Namespace namespace program { // Define class public class check { // Define main method public static void Main(string[] args) { //Assign the number which need to be checked if it is even or not int number = 8; bool ifitisEven; //Logic to check if ithe given number is even or not ifitisEven = (number % 2 == 0) ? true : false ; Console.WriteLine(ifitisEven); } } }
Output:
Conclusion
In this tutorial, we understand the ternary operators’ concept in C# through definition and then understand the working of ternary operators in C#. Then we understand different C# programs using the nested ternary operator and simple ternary operator and their working using programs with their output snapshots included with the results of the programs in it.
The above is the detailed content of C# Ternary Operators. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.
