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?
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.)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With