The C# ?: operator

Often I work for people with a Delphi background to introduce them to C#. No problem until we reach the conditional operator ?: The definition in the docs is cond-expr ? expr1 : expr2  but the examples are not that inspiring. The most common reaction is “we’re not going to use that”. Recently I found a very good way to use and demonstrate it. Let me share this.


I’m working on an application which works with an existing database. Jeremy Miller has a lovely story on those kind of animals. Mine is not to bad, I have an occasional WTF but not on a daily base. To keep the DB as far away as possible I designed a  couple of strongly typed datasets and built a set of components to fill these. Instead of an alien database I now have my dataset. But I’m still not sure what’s inside. That’s where the ?: comes to my rescue. Take this code



Indato.Data.Schemas.School.OPLOVKRow dr = OPLOVK.OPLOVK[0];
TextBoxOmschrijving.Text = dr.IsOPMERKINGNull() ? “” : dr.OPMERKING;
 

dr is a strong typed row. The problem is that I can never be sure if it doesn’t contain a null value. Trying to set the Text property of a Textbox to null will throw an exception. The typed dataset has an IsxxxNull method for every field. This is a boolean test, if it evaluates to true the empty string after the ? is used, if it evaluated to false the contents of the field, that’s the expression after the :, is used .


Fits the docs and very worthwhile using.

This entry was posted in Coding. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • HM

    Good stuff! Thanks

  • Anonymous

    At first sight, by rehashing your code
    x = ((x !=null) || (x!= “”)) ? 1 : 2

    But the type of x is ambiguous

    Is x is a string this does the trick

    x = string.IsNullOrEmpty(x) ? “2″ : “1″

  • Debashis Pyne

    how can i do the following:

    if((x != null) || x( != “”))
    x = 1
    else
    x=2

    Thanks,
    Debashis

  • teetrah

    Right. Here’s an example that I’ve found useful.

    x != null ? x != string.Empty ? x : null : null;

    If x is not null then check if it is an empty string. If not use x’s value otherwise use null if x is an empty string or if it’s null.

  • teetrah

    can’t you do this sort of syntax with more levels then just one?

    for example:

    x != null ? x : y == null ? a : z

    I think you can do something like that. Not sure if that exact syntax will work but I think I did something like this somewhere recently.

  • http://codebetter.com/members/pvanooijen/default.aspx pvanooijen

    Thanks. Still read after 5 yeras :)
    That was indeed a welcome addition :)

  • Marco

    I know this post is pretty old, but I stumbled across this but thought i’d just bring this up here as it is related.

    To check for null-values in C# you can use the ?? operator instead (Since version 2.0).

    See the reference here
    http://msdn.microsoft.com/en-us/library/ms173224.aspx

    In short:

    Foo f;
    if(mayBeNull != null)
    {
    f = mayBeNull;
    }
    else
    {
    f = otherFoo
    }

    Translates to:

    Foo f = mayBeNull ?? otherFoo;

  • http://petersgekko.codebetter.com pvanooijen

    True, Mel’s example is perhaps too simple becaus all three parts of his operation are logicals.

    The first one has to be logical, the other two don’t. Like the strings in the original post.

  • Syklo

    I really prefer a single line code more elegant. For a line like inmediatly up… i prefer:

    Que güey… a esto es a lo que se llama una redundancia. En vez de escribir

    txtFirstName.Enabled = EditMode ? true : false;

    simplemente

    txtFirstName.Enabled = EditMode;

  • Mel Grubb

    I prefer to use the Trinary operator to make it clear that a value MUST be set on a property, particularly on UI code. For instance, I’ve seen far too many examples of an “EnableControls” method that degenerate into a lot of if/else if/else branches that are too hard to follow. Later, when the rules become more complicated, it’s common to find yourself in a situation in which enabling logic develops holes, and the only way to get a control enabled again after it’s been disabled is to perform some obscure “around the horn” operation.

    For properties like Enabled, or Visible, my personal standards demand that values are set in a single line, using the Trinary operator, or IIF in VB (Although that brings up its own set of problems).

    For instance:
    txtFirstName.Enabled = EditMode ? true : false;

    The Enabled IS, without fail, GOING to be set to one of these two values. It can’t be forgotten, and there are no logic holes to fall through.

  • http://codebetter.com/blogs/peter.van.ooijen/ pvanooijen

    Absolutely.
    Maintainability is far better. It just takes 2 minutes of learning. Nothing wrong with that

  • dwayne w

    I agree with everything said in this article, and the comments made by the other posts. I don’t agree with Juval Lowy’s C# Coding Standard where 2.29 states that we should avoid using the trinary conditional operator. One line of code beats 8 lines any day of the week and IMHO is a lot easier to read.

  • http://jaysonknight.com/blog jayson knight

    I find myself using ternary anytime I have a one line conditional, i.e.

    if(something)
    doSomething;
    else
    doSomethingElse;

    =
    something ? doSomething : doSomethingElse

    It’s much more terse/readable IMO

  • http://codebetter.com/blogs/peter.van.ooijen/ pvanooijen

    I’ve heard that name to. But didn’t recognize it’s meaning.
    Just looked it up op Wikipedia, http://en.wikipedia.org/wiki/Ternary
    Trinary is a synonim, there you start recognizing the word three.

  • http://codebetter.com/blogs/darrell.norton/ Darrell Norton

    I’ve heard it called the ternary operator. It’s nice if your if statement has 2 simple conditions and you don’t want to create an 8-line (that’s how I do my braces) statement.

  • http://codebetter.com/blogs/peter.van.ooijen/ pvanooijen

    The IIF function is handy but afaik it works with parameters “typed” as object. The nice extra of the ? operator is that it does perform type checking.

  • John Fiala

    In VB6, this was known as the IIF() function. I used it quite a lot there, and am happily using this new version in C#.

  • http://www.dotnettricks.com/ frgas

    i do this all the time, especially in data binding expressions in an asp.net page.