Using C# 3.0 Features with .NET 2.0

With Visual Studio 2008 Microsoft also updated the C# language. C# 3.0 brings several new and useful features that are described in a MSDN article.

Visual Studio 2008 will always compile with the new C# 3.0 compiler even when you select .NET Framework 2.0 as target framework in your project.

This raises an interesting question: is it possible to use the new features of C# 3.0 even when you use .NET Framework 2.0? And which new features can you use?

I went through the list of new features in the MSDN article and tried them. Here are my findings:

  • Implicitly Typed Local Variables and Arrays – works
  • Object Initializers – works
  • Collection Initializers – works
  • Extension Methods – works when defining a class ExtensionAttribute (see comment below)
  • Anonymous Types – works
  • Lambda Expressions – works
  • Query Keywords – compiler error CS1935 (missing reference to System.Core.dll and System.Linq); requires .NET 3.5
  • Auto-Implemented Properties – works
  • Partial Method Definitions – works

Summary: most of the new features of C# 3.0 work even when still using .NET Framework 2.0. The two most interesting features (extension methods and Linq) however require additional assemblies that are part of .NET Framework 3.5 and thus can’t be used with .NET Framework 2.0.

However, since .NET Framework 3.5 consists of 2.0 with some additional assemblies it might be possible to update to 3.5 without to much cost/pain.

Edit 2008-08-25: Sergey pointed out that Extension Methods work if you simply define a class ExtensionAttribute derived from Attribute.


2 thoughts on “Using C# 3.0 Features with .NET 2.0

  1. Just add this code to your project to make extension methods work:

    namespace System.Runtime.CompilerServices
    public class ExtensionAttribute : Attribute

  2. That’s true. Just defining an ExtensionAttribute class is enough to make it work. Thanks Sergey!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s