Visual Studio 2008's multi-targeting support for compiling projects to
different versions of the .NET Framework is very powerful. Multi-targeting is a
compelling feature because it enables users to
continue working on solutions that target .NET Framework 2.0 and 3.0 while
upgrading to the latest and greatest IDE. What isn't obvious is that all
projects, regardless of target, are compiled with the C# 3.0 compiler. That
means users can employ many of the new C# 3.0 language features in legacy projects. The only language features that can't be used are
those that require library support from .NET Framework 3.5, in essence, LINQ,
Expression Trees and Extension Methods. Implicitly-typed local variables, lambda expressions, auto-implemented
properties, object and collection initializers, and anonymous types are all fair
game. It's sort of like having C# 3.0-lite or C# 2.5.
Interestingly,
it has recently been
discovered that even Extension Methods can be used in projects targeting .NET
Framework 2.0 and 3.0. All that must be done to enable this support is to create a new System.Runtime.CompilerServices.ExtensionAttribute.
using System;
namespace System.Runtime.CompilerServices
{
public class ExtensionAttribute: Attribute
{
}
}
This trick does have flaws. There are potential scoping issues that occur
when an assembly containing a custom
System.Runtime.CompilerServices.ExtensionAttribute is referenced by a project
that targets .NET Framework 3.5. A compiler warning is generated stating that
"the predefined type 'System.Runtime.CompilerServices.ExtensionAttribute' is
defined in multiple assemblies in the global alias." However, this is only a
minor irritation. In my tests, Extension Methods still worked properly despite
the warning.
The ability to use C# 3.0 features in .NET Framework 2.0 or 3.0 projects is
very powerful. It helps users get comfortable with the new syntax without having
to upgrade projects to .NET Framework 3.5. Viva la C# 2.5!