Why are some C#4 features allowed even when targeting 3.5?
We upgra开发者_运维百科ded to VS 2010, but we haven't yet upgraded to .NET 4.0. All of our projects are still explicitly targeting 3.5.
Today, a developer checked in code that looked like this:
delegate T Generator<out T>();
As far as I know, "in T" and "out T" are C# 4.0 features. According to our build server, which doesn't have .NET 4.0 installed on it, I'm right. The check-in broke the build. But, why the heck does it build on his machine? Why is VS just ignoring the target framework for the project?
Other C# 4.0 features, like the dynamic keyword, do not build on the developer's machine.
The C# spec is developed separately from the CLR. This means that if a C# feature can be translated into code for an earlier version of .NET, it can still be used when targeting the earlier version of the framework.
They are language features which require the C# 4 compiler, but not the .NET 4.0 framework to execute. So as long as all the machines that will be building have a C# 4 compiler you should be able to use those new features without requiring anything extra to be installed for your users.
To avoid this, use Project + Properties, Build tab, scroll down, Advanced, Language Version = "C# 3.0"
Some of the new language features don't depend on a new version of the CLR. For instance, you can use some of the C# 3.0 features when targeting .NET 2.0 (extension methods, lambda expressions, object initializers, or even query syntax if you provide an implementation for the Linq operators, like LinqBridge does). These features only depend on the compiler, not on the CLR (in .NET 3.5 the CLR is the same as in .NET 2.0).
Similarly, covariance and contravariance don't depend on the .NET 4.0 CLR, they're purely a language feature, so you can use the in
/out
modifiers when you target .NET 3.5. On the other hand, dynamic typing depends on the DLR (Dynamic Language Runtime), which ships with .NET 4.0, so you can't use dynamic
when targeting 3.5
精彩评论