C# ?: Operator

The ?: operator, also known as the conditional operator, is utilized to determine the value returned based on the evaluation of a Boolean expression. Its functionality revolves around the concept that if a Condition-Expression holds true, the resulting value is obtained by evaluating and utilizing Expression1. Conversely, if the Condition-Expression is found to be false, the value is determined through the evaluation of Expression2.

Condition-Expression ? Expression1 : Expression2

?: operator

This operator presents a viable substitute for the traditional if...else statement, offering a concise and efficient approach to conditionally assigning values. By employing the ?: operator, developers can streamline their code and enhance its readability by encapsulating conditional logic in a single line of code..

Consider the following example :

MessageBox.Show((10 > 9 ? "higher" : "smaller"));

is same as

if (10 > 9) { MessageBox.Show("higher"); } else { MessageBox.Show("smaller"); }

Both statements returns same result.

Full Source C#
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int a = 1; bool b = (a == 1 ? true : false); MessageBox.Show(b.ToString()); //The following if..else..statements return the same result if (a==1) { MessageBox.Show("true"); } else { MessageBox.Show("false"); } } } }