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 alw开发者_如何学JAVAays 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?
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.
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.
With respect to it's usage.
It is not bad with regards to execution, as already mentioned it is just syntax sugar and gets replaced at compile time.
When coding, I think it's use is mixed. For example:
I think this ok. It's easy to see what the value is
var a = "test";
Not quite so good, many people have to scroll in the IDE to actually understand the code, which is a pain.
var b = SomeReallyLongNameSpace.SubNamespace.Namespace.Class.Enum.Value1;
This is fine, you know what the result is because a clearly defined method.
var c = GetString();
You have no idea at a glance what is returned, this isn't helpful and would be better defined rather than using the var keyword.
var d = GetSomething();
about var: it is pure syntax sugar and compiler trick. typing var you ask a compiler to guess type based on right hand side of expression. this can be easily done compiling to .net 2.0. Linq might not work because it uses assemblies from .net 3.5
var was introduced to hold the instances of anonymous types in C# 3.0.
In .net2.0 may be the VS2008 or C# compiler must be replacing it with the actual type which is alraedy known at design-time and if you already knew the type while coding why would you use var! :)
精彩评论