Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this ternary operation fails?

Tags:

c#

I have 2 pieces of code one using if condition and other using the ? operator.

Both are defined successively within same function scope. But the statement using ? operator throws compile error? Is something wrong with this piece of code.

if (IsCount)
       filterParameterOriginTime.Values = new[] { new DateTime(2013, 7, 1).ToString() };
else
       filterParameterOriginTime.Values = new[] { lastPollTime.ToString() };

// IsCount ? filterParameterOriginTime.Values = new[] { new DateTime(2013, 7, 1).ToString() } : filterParameterOriginTime.Values = new[] { lastPollTime.ToString() };
like image 842
ckv Avatar asked Jan 29 '26 12:01

ckv


1 Answers

Simply, you have the operator backwards, try this:

filterParameterOriginTime.Values = IsCount 
    ? new[] { new DateTime(2013, 7, 1).ToString() } 
    : new[] { lastPollTime.ToString() };

That said, Henk raises a good point about readability. Aim for readable code versus unnecessarily terse code. I generally tend towards if statements in most cases.

like image 77
Adam Houldsworth Avatar answered Jan 31 '26 02:01

Adam Houldsworth