Initialize implicitly typed local variable to IList

Rauland picture Rauland · Apr 20, 2011 · Viewed 8.7k times · Source

I understand that implicitly-typed local variables must be initialized.

I know that result will be an IList so could I somehow say that var result will be an IList?

var result; //initialize to something 

if( x < 0)  
{  
    result = (from s in context.someEntity  
              where s.somecolumn = x  
              select new { c1 = s.c1,c2=s.c2}).ToList();  
}

if(x >= 0)  
{  
    result = (from s in context.someEntity  
              where s.someOtherColumn = x  
              select new { c1 = s.c1,c2=s.c2}).ToList();  
}

foreach(var y in result)  
{  
    //do something . UPDATE 1: Retrieve y.c1, y.c2

}  

Answer

taylonr picture taylonr · Apr 20, 2011

No they can't be "var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function."

Since you're not initializing to an interface, it won't work.

http://msdn.microsoft.com/en-us/library/bb384061.aspx