Initialize implicitly typed local variable to IList
I understand that implicitly-typed local variables must be initialized
.
I know 开发者_StackOverflow中文版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
}
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
If you know you want it to be an IList
, why not just declare it as an IList
?
Using var
for uninitialized variables is (IMO) pretty unreadable.
Do this:
var result = default(IList);
You might be able to do something with a ternary operation:
var list = (x < 0) ? ... : ...
but really, that would be pretty painful to read. With your code as posted I think I'd just stick with
IList result;
for readability.
If you are using System.Collections.Generic in your code then the only option available is
var list = (x < 0) ? ... : ...
If you try to use IList in the above scenario you will get the error Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.IList'. An explicit conversion exists (are you missing a cast?)
But if you are using System.Collections you can use
IList result;
精彩评论