Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

The code you are attempting makes your code very difficult to read. Like BrokenGlass said, you are trading clarity for raw character count.

This is the only "one line" solution C# supports.

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

But I encourage everyone to expand this to at least two lines (my preference is four with the braces).

Purpose of the solution aside, following one-liner might give you end result you want while using ??. Do not try this at home though.

filters.Add(FilterType.DateFrom, fromDt ?? DateTime.MinValue)

The idea is to set DateFrom to min possible value, essentially adding an open filter.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top