Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disallow var keyword under .net 2.0 target?

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?

like image 960
DixonD Avatar asked Aug 04 '10 07:08

DixonD


3 Answers

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

like image 129
Jon Skeet Avatar answered Oct 24 '22 04:10

Jon Skeet


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.

like image 36
Dean Harding Avatar answered Oct 24 '22 04:10

Dean Harding


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.

like image 1
dahlbyk Avatar answered Oct 24 '22 03:10

dahlbyk