Cody
Cody

Reputation: 8944

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.

Upvotes: 2

Views: 1673

Answers (3)

THX-1138
THX-1138

Reputation: 21730

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.

Upvotes: 0

Devin Burke
Devin Burke

Reputation: 13820

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).

Upvotes: 2

James Cronen
James Cronen

Reputation: 5763

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.

Upvotes: 7

Related Questions