문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top