I created new project in Visual Studio with target framework 2.0. But even if I left somewhere var
keyword Visual Studio successfully compiles project. Is this the correct behavior as var
is 3.0 feature? Is there any settings to prevent code with var
to be compiled?
views:
132answers:
4var
is a feature of C# 3.0, but it doesn't require any framework features. In other words, it's absolutely fine to use within a project targeting .NET 2.0. The same is true of many other features - anonymous types, automatic properties, lambda expressions etc.
See my versions article for more information. (I need to update it for C# 4 at some point...)
If you want to restrict yourself to C# 2.0, you can specify the language version by clicking on "Advanced" in the Build tab of the project properties, IIRC. (It's definitely there somewhere, but I'd rather have a cup of coffee than check for the exact location right now.)
As long as your project will always be compiled with Visual Studio 2008 or newer, you're safe to use C# 3.0 features. The .NET 2.0 target only restricts what libraries you can use, not what language features.
var
is purely a compile-time feature, once the assembly is compiled, the compiler inserts the actual type and the fact that you had used var
is "lost".
So a project that's targetting version 2.0 of the framework can still make use of the var
feature, because it doesn't actually affect the outputted assembly in any way.
Either do full text replace of var by 1var1 and manually replace them or use pre 3.0 versions of compiler.