Dave Burke - Freelance .NET Developer specializing in Online Communities

A freelance .NET Developer

Conditional or Ternary Operators in C#

You get hooked in C#:  how can I write this in less code?  How can I be more economical?

I've used the ?: conditional operator occasionally over the last couple of years, but didn't take the time to “get it.“

In short, it provides a one-time statement to replace an if(){} else {} sequence, like so:

txtWork_phone.Text = ue.work_phone != string.Empty ? TextUtils.PrettyPhone(ue.work_phone) : string.Empty;

instead of

if (ue.work_phone != string.Empty)
{
 txtWork_phone.Text = TextUtils.PrettyPhone(ue.work_phone);
}
else
{
 txtWork_phone.Text = string.Empty;
}

A mistaken approach to using the Conditional Operator would be something like

i < j ? i++ : j++;

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

k = i < j ? i++ : j++;

The trick is in utilizing the initial assignment.  Cool C# tidbit for the day.  Big thanks to a newsgroup post authored by Jacob Yang helping me to happily get it.

Comments

Elph said:

you also could use for something more complicated like:

a==b?c:(a>b?d:(a<b?e:f));

the only bad thing is that is hard to read

# March 27, 2004 4:25 AM

Dave Burke said:

Elph, Thanks for providing the extreme! Wow, I'll have to read over that statement a few times...
# March 27, 2004 8:14 AM

fahad said:

Elph, Thanks for providing the extreme! Wow, I'll have to read over that statement a few times

# August 2, 2007 4:21 PM

Gotisch said:

Isnt that overcomplicated?

a==b?c:(a>b?d:(a<b?e:f));

if a != b and a>b == false then you dont need to check if its smaller.. (a<b) it obviously is so f would never be used, no?

a==b?c:(a>b?d:e); returns the same..

# August 2, 2007 4:47 PM

ermancetin said:

Gotisch, you'r right. f value will never be returned.

# September 2, 2007 9:30 AM

Monkey said:

aha! Thanks for this!!! Didn't know what it was called, and didn't know exactly how to use it! Eases up coding a LOT!

-Monkey

# August 11, 2008 8:01 PM

Tintin said:

The only reason it's hard to read is because the example used was very poor.

A better example would be:

Console.WriteLine("There are {0} {1}", numEmails, numEmails > 1? "messages" : "message");

A quick way to add smart pluralization on one line.

# September 17, 2008 11:23 PM

Alex James Brown » C# Ternary conditional operator – Question mark in an if statement said:

Pingback from  Alex James Brown &raquo; C# Ternary conditional operator &ndash; Question mark in an if statement

# September 9, 2009 7:30 PM

fe said:

how to use ternary operators in java???

# November 24, 2009 6:58 AM

Kalpesh joshi said:

int eight = 8;

string answer = eight == 5 ? "true" : "false";

# April 7, 2010 2:25 AM

-S said:

I have an example myself for when you don't want to make an assignment but a direct return.

Please note that I have not tested this yet but lexically/syntactically it is correct according to my IDE

return "conditionOne" ?

      "conditionTwo" ?

      "conditionThree"

      : false

      : true

Should give the following effect ( According to my assumption)

If condition one is true return false

else return true

If condition two is true return false

else return true

If condition three is true return false

else return true

(I used this for a collision detection based on TileTypes on a 2D grid, if any of the inaccesable types were present the detection method would have to return false and deny acces)

# May 25, 2010 6:42 AM

-S said:

To make your life a lot easier, get ReSharper, and practice. Once you get used to it ternary will be the only thing you will want to use.

# June 3, 2010 2:55 PM

kikus said:

отличный пост, автор пиши ещё

# June 16, 2010 3:42 AM

norabh said:

((a>b && a>c)? "a"b>c?"b":c

# March 21, 2011 12:17 PM

Zan.exe said:

This tutorial was awesome. It helped me learn how to create a boolean toggle in one line.

isActive = isActive == true ? false : true;

# May 21, 2011 3:28 PM

swapna said:

can anybody tell me about ternary operators plz...

# July 4, 2011 1:28 AM

upendra singh parmar said:

this example is so helpful for me.thanks

# August 4, 2011 6:47 AM

!false said:

Zan.exe,

isActive = !isActive;

# September 22, 2011 8:30 AM

!false said:

I like ternary for lazy loading:

private static SomeFactory inst;

public static SomeFactory getInstance() {

 return inst != null ? inst : (inst = new SomeFactory());

}

# September 22, 2011 8:37 AM

Jit said:

Can anybody tell us which one is better in terms of performance?

# October 1, 2011 12:11 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)