1

I'm having troubles with this ternary line:

var userFromContext = IsOwner ? db.Owners.Where(o => o.UserName == username) 
                              : db.Users.Where(u => u.UserName == username);

It's giving me this error message:

Type of conditional expression cannot be determined because there is no implicit conversion between System.LINQ.IQueryable<Owners> and System.LINQ.IQueryable<Users>.

Why should it care if I'm assigning it to a var variable?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Ron
  • 1,721
  • 1
  • 19
  • 43
  • 2
    related: [var keyword runtime or compile time?](http://stackoverflow.com/questions/3632918/var-keyword-runtime-or-compile-time) – Conrad Frix Nov 18 '11 at 05:54
  • 1
    Don't confuse javascript's var and csharp's var. In fact, don't use csharp's var unless you have to (such as with anon types). – Amy B Nov 18 '11 at 16:14

3 Answers3

11

Because the variable has to be of some type.

"var" doesn't mean "untyped". It means "dear compiler, please figure out what the type of this variable should be based on the expression that I'm assigning to it".

In order to do that, the compiler must first understand what the type of expression is, and it can't do that because two branches of your ternary operator are of different types.

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • Ah. I was thinking since `var userFromContext = db.Users.Where(u => u.UserName == username);` works on its own, it shouldn't be a problem to determine it's type on the fly after evaluating the condition. – Ron Nov 18 '11 at 05:56
  • 1
    @Ron, no, that is not the case. "var" is not some new shiny feature, but a mere shortcut; a way to shorten your code while keeping its nature unchanged. – Fyodor Soikin Nov 18 '11 at 05:57
3

A ternary operator must have a specific, common, return type. You can fix this by casting them both to IEnumberable.

Ry-
  • 218,210
  • 55
  • 464
  • 476
3

Because the var is just a placeholder for a static type. The type has to be known at compile time. If the type depends on the data, then the compiler cannot know what type it is. Rather than a var, use the dynamic keyword if you really want to use the above construct:

dynamic userFromContext = IsOwner ? db.Owners.Where(o => o.UserName == username) 
                                  : db.Users.Where(u => u.UserName == username);
flipchart
  • 6,548
  • 4
  • 28
  • 53
  • 1
    If you use `dynamic`, then you won't be able to use LINQ operators on it down the road, because `dynamic` doesn't work with extension methods. – Fyodor Soikin Nov 18 '11 at 05:56
  • That's correct, but I was trying to keep the construct similar to the OP's original – flipchart Nov 18 '11 at 06:08