C#: How to define implicit type variable inside IF block and use outside

70 views Asked by At

I want to do something like this:

var myQuery;
if (someParam > 0) 
{
    myQuery = from x in myTable where x.myValue > someParam select x;
}
else {
    myQuery = from x in myTable select x;
}

The problem is I can't do this because you apparently cannot define an implicit variable without declaring it first, nor can you re-declare an implicit variable after you've declared it.

Assuming that I will not know the return type of the data (the whole point of an implicit type variable), what's the appropriate way to do this?


EDIT:

The first answer below works well if your types are clearly defined, but what about something like this?

var myQuery;
if (includeSomething == true) 
{
    myQuery = from x in myTable select new { f1 = x.field1, f2 = x.field2 };
}
else {
    myQuery = from x in myTable select new { f1 = x.field1, f2 = x.field2, x3 = x.field3 };
}
1

There are 1 answers

0
Rahul On

Yes, in such case declare it strongly typed like

var myQuery;

to

IEnumerable<your_type> myQuery;

You can as well do this using a ternary operator like

var myQuery = (someParam > 0) ? from x in myTable where x.myValue > someParam select x : from x in myTable select x;