views:

255

answers:

2

What are the C# 3.0 language features we can use in an application that targets .Net 2.0 framework ?

PS:I know few like Lambda expressions and var keyword

+5  A: 

I have an article on this very topic.

In brief:

Supported:

  • Automatically implemented properties, implicitly typed local variables and arrays, object and collection initializers, anonymous types, partial methods, lambda expressions converted into delegate types.

Partially supported:

  • Extension methods (requires an attribute) and query expressions (requires something like LINQBridge to be useful)

Not supported:

  • Lambdas converted into expression trees

In fact, I have heard that conversion into expression trees is available with the aid of Mono's implementation of System.Core. I haven't tried it yet though... I keep meaning to do so (and then update the page).

Jon Skeet
Yes, I suspect the expression tree stuff would work fine, as long as there is a suitable Expression class. Of course, the exact requirements of that class are not documented in the spec, and if *anything* is wrong the compiler explodes in a **very** messy way (much uglier than you would expect). I had much fun just trying a small part of it (http://marcgravell.blogspot.com/2009/04/re-implementing-expression-for-compact.html) - the mono option makes more sense for a full version.
Marc Gravell
+1, Thanks Jon and Marc :)
Prashant
+4  A: 

Please see here:

Using C# 3.0 (.Net 3.5) syntax in a .Net 2.0 application

For a complete run down of what you can and can't do when targeting the .NET 2.0 Framework and using C# 3.0.

In summary:

Extension methods sort-of work, however, they require "System.Runtime.CompilerServices.ExtensionAttribute" in order to work, and this type is found within the System.Core DLL (which is not strictly part of the .NET 2.0 framework).

Query Syntax cannot be used "out of the box" so-to-speak, however, it can be used if a 3rd party DLL (like LINQBridge) is used. This DLL effectively re-implements many of the "missing" types that you need to perform LINQ when targeting the .NET 2.0 framework. It also implements the "ExtensionAttribute" type needed for Extension methods to work, so simply adding/referencing the LINQBridge DLL from your project will enable LINQ, Query Syntax/Expressions and Extension Methods!

CraigTP
Jon beat me to it. In a strange twist of fate, the very first comment on the blog post that I've linked to is from Jon Skeet (!)
CraigTP
Re the second "You can't" - you can use query syntax - simply that they aren't present unless you use something like LINQBridge.
Marc Gravell
@Marc - You're correct. Thanks for pointing that out. I have edited my answer to reflect this fact.
CraigTP
The facts are very interesting... I'll accept your answer, as Jon got plenty of reputation :P
Prashant