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
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.