Monday, October 10, 2005

C# Ternary Operator

Although it is sometimes misused, the ternary operator (also called the conditional operator, although I personally prefer ternary) in C# can be quite a timesaver. For those who don’t’ know, it is roughly equivalent to the IIF function in VB.



The C# language specification contains a really convoluted definition for what essentially amounts to a very simple operation. In my own words, the syntax for using the ternary operator is as follows:



    test-condition ? true part : false part
;



In other words, if “test-condition” evaluations to true, the true part code will execute. Otherwise, the false part code will execute. It’s like an if-then-else bundled into one statement. In fact, the statement above may be rewritten to:




if
(
test-condition)


{

    //true part code here

}

else

{    //false part code here

}



Arguably, a programmer could get carried away with what amounts to a shortcut. One great use of the ternary operator that I’ve found, though, is assigning the value to a variable at the time of declaration based upon a specified condition. For example, reading the contents of a config file, and storing the value in a variable.



Note that when reading from a config file, if the specified key does not exist, the value returned will be null. If you then try to perform a string operation (like testing the value of the string), you’ll end up with a nasty little System.NullReferenceException. To avoid this, I use a technique with the ternary operator that allows me to grab my value, and account for the possibility of null all in one statement. Here’s an example:




//read a setting from the config file,


//and assign it to the mySetting string:

string mySetting = ConfigurationSettings.AppSettings["KeyName"] != null ?
      
ConfigurationSettings.AppSettings["KeyName"] : string.Empty;



Another great use is for the ternary operator is when retrieving values from a Data Reader or Data Table. You can use a similar approach to the example above to test for a condition of “== DBNull.Value” before performing any operations on the object that may potentially have a null value.

1 comment:

Anonymous said...

Not just a C# thing; it comes from C.