Wednesday, October 24, 2007

C# 3.0 Features: Var

"var" is one feature of C# 3.0 that has called for much debate. What is "var" and when can it be used, has already been dealt in many blogs and Microsoft documentation. So, I'll not be writing about it here. What I'll talk about is why var is not allowed to be passed around in functions i.e. why do you get this compile-time error:

the contextual keyword var may only appear within a local variable declaration

when you try to accept a parameter of type var. Considering that var can accept anonymous types, it is very convenient to tossing it around in function calls. But that isn't allowed. Let's see why:

Let's approach this using the Contradiction theory. Let's assume that this doesn't give any error and is allowed. Now, when the code is built the actual type of var has to be resolved. And since the var, in our case, hasn't been initialized (remember it's a function parameter), the compiler doesn't know to what type the var should be resolved. And that's why the compiler can't allow this. Let's also assume that the compiler is intelligent enough to infer its type from the invocation call of the method i.e.


private void ExecuteThis(var intVar)

Looking at "ExectueThis(5)", let's say, the compiler infers intVar is of Int32 type. Looks good to me if the compiler could do it. But what if ExecuteThis is called from somewhere else also and a string is being passed to it.


Probably we can say that don't allow the second call as from the first call we have already determined intVar to be Int32. But what if all this is in a class library, where you can't determine the sequence of function calls i.e we don't know whether first function call will be made first or the second one will be made first.

So, essentially, there is no way the compiler can tell, for sure, what type the var parameter is. And thus var can't be passed around in functions. I don't see a great use of var in general programming except if you are using LINQ. It helps you to avoid declaring custom types for each resultset that is returned from a LINQ query. var is more tailored for use with LINQ

No comments: