Net-informations.com
SiteMap  | About    

C# ?: Operator

?: Operator returns one of two values depending on the value of a Boolean expression.

  Condition-Expression ? Expression1 : Expression2

If Condition-Expression is true, Expression1 is evaluated and becomes the result; if Condition-Expression is false, Expression2 is evaluated and becomes the result.

We can use ?: Operator is an alternative to the if...else statement.

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.




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");
			}
		}
	}
}






net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.