C# - The ternary operator

Just when I thought I'd got C# syntax sorted, I come across a statement which looks like some sort of alien script language.  So I decided to look it up and see what it's all about. The statement is what's known as the ternary operator. Simply put it's a way of doing an if else statement in one line of code. Making it more readable and I assume more efficient.

Lets say for example we have a function which returns a dataTable, in some cases the dataTable may have a null value, and trying return the it would cause an exception. So we would have to return null in this case.  The usual syntax might go something like.

if (dt == null)

   return dt;

else

  return null;

 

But using the ternary operator we can distill this down to one line:

 

 

return (dt == null) ? null : dt;

 

A lot nicer, once you understand it.  I believe this also works in JavaScript, but I haven't tested it.


Posted by: Dean
Posted on: 11/14/2008 at 6:26 AM
Tags: , , , ,
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (1) | Post RSSRSS comment feed