Cover

Visual Studio 2008 for .NET 2.0 Development - An Interesting Quirk

November 28, 2007
No Comments.

I’ve been converting some projects to Visual Studio 2008 (but not .NET 3.5) to see if I like the new IDE better than 2005.  So far I can’t tell a big difference (though the improved Script debugging is nice).  I did find out something interesting…

I use the ‘prop’ snippet (if you don’t know what this is, in 2005 or 2008 type ‘prop’ {no quotes} and hit tab twice) to add simple properties.  In 2005 it stubs out the field and the property.  But in 2008 it stubs out an implicit property.

If you are not familiar, implicit properties look like this:

class Foo
{
  public int MyProperty { get; set; }
}

```csharp

The compiler creates a field for you at compile time automatically.  Cool, right?  Well I was writing some new code and hit the 'prop' snippet in 2008 and got the new syntax but I was perplexed.  Doesn't 2008 know I am running against NET 2.0?  This certainly won't work, right?

Nope...it works.  Why? Because you are targeting the 2.0 Framework but using the C# 3.0 compiler.  Consider the following code:


```csharp
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication8
{
  class Program
  {
    static void Main(string[] args)
    {
      Foo foo = new Foo() { MyProperty = 15 };
      Console.WriteLine(foo.ToString());

      string[] names = new string[] { "Shawn", "Bob", "Alice" };
      Console.WriteLine(names);

      // CAN"T USE LINQ as System.Core and 
      // System.Linq require .NET 3.5!
      
      //var coll = from n in names
      //           select n;
      //Console.WriteLine(coll);

      Console.ReadLine();
      
    }
  }

  class Foo
  {
    public int MyProperty { get; set; }

    public override string ToString()
    {
      return MyProperty.ToString();
    }
  }
}

```csharp

The simple property defined in the Foo class works because the C# compiler is creating the correct code for the .NET 2.0 Framework to use.  Notice that I tried to do some LINQ code but that requires System.Core and System.Linq (both of which are only available in the .NET 3.5 Framework. As long as you are using C# 3.0 features that don't require .NET 3.0 or 3.5 assemblies, the compiler features still work.  If you were paying attention, I used the object initializer syntax too.

The thing to think about is that if you are using VS 2008, you're using the new compilers (VB and C#) but targetting the right version of the Framework.  I don't know this for sure, but I suspect that targetting .NET 2.0 is actually targetting .NET 2.0 SP1.  I'll know soon when I try to deploy my first site to my 2.0 host.

This may be a boon for people stuck on the .NET 2.0 framework for deployment but want to use some (not all) of the new C# 3.0 features.  I haven't tried this in VB...i'll leave that to my VB MVP's!