Report Offensive Message

Use of ternary operator
I came up with my own class framework once for transferring data back and forth between a web page and a database in ASP.Net 1.1, and I found the ternary operator really helped make it less complicated. It was a situation that helped me figure out why some .Net and Java programmers preferred using code generators, because there was a lot of repetitive code involved. One of the things I did with the ternary operator involved value conversion. I'd write something like:

objFieldValue = (record["field"].IsNull()) ? 0 : record["field"];

A lot more efficient than having to type this kind of pattern 50 times as:

if (record["field"].IsNull())
{
objFieldValue = 0;
}
else
{
objFieldValue = record["field"];
}

The curly braces could've been left off in this case, but that potentially leads to logic errors if additional code needs to be added to a clause.
Posted by Mark Miller
12th Jun 2011