In the code below, I need to set “Variable1” to an arbitrary value so I don’t get into scope issues further below. What is the best arbitrary value for a variable of type var, or is there a better way to avoid the scope issue I’m having?
var Variable1;
if(Something == 0)
{
//DB = DatabaseObject
Variable1 =
from a in DB.Table
select new {Data = a};
}
int RowTotal = Variable1.Count();
Well, you could do:
This is effectively “typing by example”. To be honest, I’d try to avoid it – but it’s hard to know exactly how I’d do so without seeing the rest of the method. If possible, I’d try to keep the anonymous type scope as tight as possible.
Note: in this case you could just select
ainstead of an anonymous type. I’m assuming your real use case is more complex. Likewise if you genuinely only need the row total, then set that inside the braces. The above solution is only applicable if you really, really need the value of the variable later on.