Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using the keyword var bad in C# 2.0?

I read an article about using C# 3 features in C# 2 where you can for instance type var x = 2; and even if the project is a 2.0 project, the Visual Studio 2008 compiler picks it up and generates the same code as it would if you type int x = 2.

But what I don't get is, should you not do this in some cases? I always thought that the var keyword didn't arrive until C# 3.. If the compiler generates the same code and I can type C# 3 code and C# 2 code exactly the same, what is the differance really, because the CLI is the same, right?

Quote from the link above

Behind the scenes, the compiler generate regular .NET 2.0 code.

Is there any difference between .NET 2.0 code and .NET 3 code?

like image 461
Patrick Avatar asked Apr 29 '10 10:04

Patrick


People also ask

Is it bad practice to use var?

var should only be used when necessary, as it was designed; and not in places where specific type declarations work fine.

Why VAR is not recommended?

Scoping — the main reason to avoid var var variables are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } .

Is VAR used in C?

What Is the Var Keyword in C#? The Var keyword is used to let the compiler infer what the type of the variable is without you having to do that thinking. With some knowledge of the language you will know that certain expression will output a certain type.

Why you should no longer use var in C#?

Overuse of var can make source code less readable for others. It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types. The complaint that var reduces readability is not shared by everyone.


2 Answers

I am afraid you are mixing up C# versions and .NET versions.

You cannot use var in C# 2.0, the compiler will think it is just an identifier. But you can use it in C# 3.0 targeting .NET 2.0, since var is just a language (C#) construct, not a .NET construct. The .NET compiler will translate it into the appropriate type in the generated CIL, so the JIT compiler will never see it and you will be completely fine.

Since the VS2008 compiler is a C# 3.0 compiler, you will have no problem using var there, regardless of the .NET version you are targeting.

like image 122
Gorpik Avatar answered Oct 04 '22 05:10

Gorpik


var is syntatatic sugar in the C#3 language which VS2008 uses. the code can still be compiled to be .net 2.0 compatible. The only issue you should have is if you need to edit those files in VS2005.

like image 21
Sam Holder Avatar answered Oct 04 '22 03:10

Sam Holder