Net-informations.com

C# ?: Operator

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

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 :

is same as

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) 2019    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About