views:

132

answers:

4

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?

+11  A: 

var 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.)

Jon Skeet
+1. /langversion (C# Compiler Options) (http://msdn.microsoft.com/en-us/library/f4ckecs0.aspx)
desco
Thanks both Jon and desco! This is exactly what I want - to restrict language features to C# 2.0.
DixonD
+1  A: 

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.

dahlbyk
The purpose why I need to restrict my code to 2.0 that it is supposed to be compiled under pure .NET Framework 2.0 afterwards.
DixonD
+2  A: 

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.

Dean Harding
A: 

Either do full text replace of var by 1var1 and manually replace them or use pre 3.0 versions of compiler.

Grozz