tags:

views:

32

answers:

2
if(){...}
else{...}
            if ( query.Count > 0 ){...}

The displayed above is a skeleton similar to the one that I use. In the first if-then-else sequence I initialize a query variable (used in LINQ) called query and then check it at the next if -statement. Still the environment says that query is not presented in the current context. If the code from the if-then statement is used alone - then no problems are observed. It seems to me that the problem is with the initialization of the variable. Do you have any other suggestions?

If you have an idea how to initialize with null value a variable that is to be queried with link - I would be glad to hear this, too. Thank you!

+2  A: 

Declare the variable before the if-else:

//replace var with the actual type, of course
var query;
if(){...}
else{...}

if (query.Count > 0){...}
Anon.
What is the real class...I expect the variable to consist a list (or in this case its first entry. So it's IQuariable type.var query; is not allowed, as it is not a real initialization.
Branimir
Typically, it's `IEnumerable<T>`, where T is whatever you're fetching.
Anon.
A: 

The problem is that the scope of the "query" variable needs to be larger than the scope in which you've defined "query".

But since you've used var, you can't declare "query" until there's enough information for the compiler to choose the type.

To resolve, simply declare the type of the variable in the desired scope (don't use var).

IEnumerable<Customer> query = null;

if ()
{
  query = ...
}
else
{
  query = ...
}

if (query.Any())

Nothing in Linq depends on the use of the var keyword. Learn more about var here.

David B