Conditional Operators

1/07/2008

I’m working on a clean up project on a C# .net app and came across the following code that is a pretty standard way to assign a value based on the value of something else.

DateTime dNow;
if (sNow == null)
{
    dNow = DateTime.Now;
}
else
{
    dNow = DateTime.Parse(sNow);
}

Most languages have what’s called a conditional assignment operator which exists for this very purpose. Here’s an example that does the same thing as the above code, but in one line.

Date Time dNow = sNow == null ? DateTime.Now : DateTime.Parse(sNow);

In addition to the benefit of saving screen real estate, I think doing it in one line is actual easier to understand…

No Comments