Search code examples
c#c#-4.0if-statementunary-operator

Conditional Statement Checking Null


I'm trying to figure out how to have a short, one line conditional statement.

If this date is not null, add the filter to the current list of filters:

fromDt ?? filters.Add(FilterType.DateFrom, fromDt);

Is there a way to do this? I know I could do..

(fromDt != null) ? "something" : "something_else", but I don't need the 'else', and would really like to just use the ?? operator for null checking.


Solution

  • What's wrong with this?

    if (fromDt != null) filters.Add(FilterType.DateFrom, fromDt);
    

    First and foremost, your code should be readable. Even if your ?? code works, I wouldn't know what it does on first glimpse.