I do not understand how this works - I am using VS2008 and using 3.0 language features like the var keyword.
Yet I can compile and run against a 2.0 framework version
How is that possible?
EDIT: Is there a website which defines the CLR, Framework and language features and backward compatability - I am quite confused by all that
Some language features are just the compiler being smart - var
being one of them. The compiled code has no trace of the fact that the variable was declared via var
.
Other features (e.g. extension methods) require support from the framework. Extension methods are recognised and advertised via ExtensionAttribute
. Likewise expression trees require the Expression
class and its subclasses.
Some other features require CLR support too - generics in C# 2 being the most obvious example. None of the features in C# 3 fully require CLR support; .NET 3.5 shipped with a service pack to the CLR, but no major changes. I suspect there are a few corner cases where the v2 CLR would have had problems with some expression trees before. (I think DynamicMethod
changed a little internally, although I can't remember the details.) There may be some verifiability tweaks too.
I have an article which describes which features in C# 3 can be used when targeting .NET 2. I'll expand this to include C# 4 soon.
The reason why is that the binary produced from the C# compiler using most 3.0 features is compatible with the 2.0 runtime. The CLR doesn't care what language or version of the language that you used, only that the binary is compatible with it's specifications.
The var
keyword is the simplest case because it simply infers the type of a local variable. The compiler then writes the explicit type out to the binary. So the following 2 lines are equivalent as far as the emitted IL
var x = 42;
int x = 42;
var
, for instance, is a compile-time feature and is in no way tied to any particular version framework (aside from the fact that it was introduced with Visual Studio 2008).
Another compile-time feature that works across framework versions (slightly to my own surprise) is optional and named arguments in Visual Studio 2010. But it makes sense that the compiler can easily generate whichever methods are necessary.
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