All posts tagged 'vs2008'

.NET Musings

Wandering thoughts of a developer, architect, speaker, and trainer


Visual Studio 2008 Compiler Tricks

So, you've targeted the 2.0 Framework in your VS 2008 project.  You are using R#, and it suggests using "var".  And it compiles...what the?

Turns out there are a lot of compiler tricks that have been included for C# developers in VS2008 that still compile down to 2.0 compatible IL.

The "var" keyword is just one instance.   The new automatic properties and object initializers are other examples.  Let's look at a very simple class, in C#, targeting the 2.0 Framework:

  1:     public class Class1
  2:     {
  3:         public string TestString { get; set; }
  4:         public String DoSomething()
  5:         {
  6:             var s = "Test";
  7:             List<string> myStrings = new List<string> { s };
  8:             return myStrings[0];
  9:         }
 10:     }

This compiles just fine. When examined in ILDasm, we get:


Note the backing field for the automatic property? Now look at like 6 in the IL below.  Definitely declared as a string.

  1: .method public hidebysig instance string 
  2:         DoSomething() cil managed
  3: {
  4:   // Code size       35 (0x23)
  5:   .maxstack  2
  6:   .locals init ([0] string s,
  7:            [1] class [mscorlib]System.Collections.Generic.List`1<string> myStrings,
  8:            [2] class [mscorlib]System.Collections.Generic.List`1<string> '<>g__initLocal0',
  9:            [3] string CS$1$0000)
 10:   IL_0000:  nop
 11:   IL_0001:  ldstr      "Test"
 12:   IL_0006:  stloc.0
 13:   IL_0007:  newobj     instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
 14:   IL_000c:  stloc.2
 15:   IL_000d:  ldloc.2
 16:   IL_000e:  ldloc.0
 17:   IL_000f:  callvirt   instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
 18:   IL_0014:  nop
 19:   IL_0015:  ldloc.2
 20:   IL_0016:  stloc.1
 21:   IL_0017:  ldloc.1
 22:   IL_0018:  ldc.i4.0
 23:   IL_0019:  callvirt   instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32)
 24:   IL_001e:  stloc.3
 25:   IL_001f:  br.s       IL_0021
 26:   IL_0021:  ldloc.3
 27:   IL_0022:  ret
 28: } // end of method Class1::DoSomething


I discovered this quite by accident while submitting some tests to the NHibernate project.  I got rejected because my code wouldn't compile.

Bottom line, if everyone is on VS2008, use everything you got!  If not, as Elmer Fudd once said "Be vewy vewy careful"

Happy coding!

Technorati Tags: ,,
Managed Windows Shared Hosting by OrcsWeb