ckv
ckv

Reputation: 10830

Why this ternary operation fails?

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() };

Upvotes: 2

Views: 92

Answers (2)

Adam Houldsworth
Adam Houldsworth

Reputation: 64467

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.

Upvotes: 11

macwier
macwier

Reputation: 1083

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

Upvotes: 3

Related Questions