blog.mha.dk
The on-line blog of Michael Holm Andersen

Ternary Operators in C#

Thursday, 25 October 2007 19:59 by mha

The C# language has a 'shortcut' to the simple if-else statement, called Ternary Operators. In short, it provides a way of reducing code like this:

if (MobilePhone != string.Empty)
{
  txtGSM.Text =
MobilePhone;
}
else
{
 
txtGSM.Text = "No number specified";
}

to this syntax:

txtGSM.Text = MobilePhone != string.Empty ? MobilePhone : "No number specified";

It takes a little getting used to, but actually it's quite nice after a while .. and it does make the code a lot less "messy".

The next thing you might want to do with Ternary Operators is to create code like this:

h < a ? h++ : a++;

However, this produces the error:  Only assignment, call, increment, decrement, and new expressions can be used as a statement.

The tricks is in the initial assignment, so the statement has to been adjusted to this:

int m = h < a ? h++ : a++;

Categories:   C#
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed
Comments are closed