Shahar Gvirtz's Weblog

Use C# 3 features from C# 2 and .NET 2.0 code (var keyword, anoynoymous types, auto-properties and more from .NET 2.0 project)

clip_image002Visual Studio 2008 and .NET 3.5 are already here, but some of us, sometimes, still need to use .NET 2.0.
Visual Studio 2008, support in a new feature called “Multi Targeting”. You can use Visual Studio 2008 ad IDE for .NET 2.0 and .NET 3.0 too. Simply, in the “New Project” form, choose the version you want.

The common between all this versions you can use VS2008 to develop for it, is that this entire versions are actually based on the same version of CLR – CLR 2.0.

.NET 3.5 based in the same version of CLR that .NET 2.0 uses. Of course, there are a lot of new features, new C# and VB.NET versions, but under the covers the same CLR works.

Why is it so important? Because theoretically, you can use some of the mew features of .NET 3.5 in .NET 2.0 when you work from VS 2008.

In this post, I'll show you some of the new C# 3 and .NET 3.5 features and how they work in .NET 2.0 project (that created and developed from Visual Studio 2008). For every feature I'll give you a look of which code is actually generated. I give you the original code, and the disassembly code from Reflector.

All the code in this post written in Visual Studio 2008 in a .NET 2.0 Console Application projects, without reference to any addition assemblies, and checked in machine without .NET 3.5.

Auto-Properties
one of the new features in C# 3 is auto-properties. because, actually, a lot of the properties we write are very simple, we don't have to write the full code (declare private variable, create getter and setter). We just have to write this:

public string Name { get; set; }

The same code of auto-properties works from .NET 2.0 projects under Visual Studio 2008. That's because the auto-properties is only a compiler trick.  Let's see how this code looks in reflector (in .NET 2.0 project, same like in .NET 3.0 project):

   1:      // Fields
   2:      [CompilerGenerated]
   3:      private string <Name>k__BackingField;
   4:   
   5:      // Properties
   6:      public string Name
   7:      {
   8:          [CompilerGenerated]
   9:          get
  10:          {
  11:              return this.<Name>k__BackingField;
  12:          }
  13:          [CompilerGenerated]
  14:          set
  15:          {
  16:              this.<Name>k__BackingField = value;
  17:          }
  18:      }
  19:  }

As you can see, what's actually happened, is that the compile create new private variable, and public property with simple getters and setters. because that's actually a compiler trick, we can use it in .NET 2.0 projects too.

Object Initializers

   1:  List<Book> books = new List<Book>();
   2:  books.Add(new Book() { Name = "Enders Game", ISDN = "13456789" });

This simple code is an example of the new Object Initializers in C# 3. But, this code works when you create a .NET 2.0 project too. Because, again, it's simple compiler trick. This is the output of the Reflector's disassemble for this code (in .NET 2.0 project under Visual Studio 2008):

   1:  internal class Program
   2:  {
   3:      // Methods
   4:      private static void Main(string[] args)
   5:      {
   6:          List<Book> books = new List<Book>();
   7:          Book <>g__initLocal0 = new Book();
   8:          <>g__initLocal0.Name = "Enders Game";
   9:          <>g__initLocal0.ISDN = "13456789";
  10:          books.Add(<>g__initLocal0);
  11:      }
  12:  }
  13:   
  14:   

Behind the scenes, this code creates a new instance of the Book object, and simply give values to the properties. Because .NET 2.0 and .NET 3.5 are actually working on the same CLR, the same code generated, and it's working on .NET 2.0 too.

"var" keyword

the keyword "var" is new in C# 3, and give us the option to declare a new variable without specify the type. the type will be the type of the value that we will put to the variable:

var i =5;

this code will work in .NET 2.0 project in Visual Studio 2008 too. because again, it's compiler code. If I'll check the Reflection's disassembly, I'll see:

image

 

Empty!!!

the compiler is smart. when i only declare a variable but never use it, it will not compile. but, if I'll change a little the code, and print this variable:

   1:  var i = 5;
   2:  Console.WriteLine(i);

then, we'll see this:

image  We can use this feature in .NET 2.0 project, because it's only a compiler trick. actually, "var" only tell the compiler to replace it with the type name of the value we use. in this example, we see that int replaced the var keyword.

More than that. we also can use Anonymous Type in .NET 2.0 project:

   1:  var i = new { Name = "Enders Game", ISDN = "123456789" };
   2:  Console.WriteLine(i.Name);

The disassembly:

image

WOW! What is this "var" keyword in the disassembly? this is .NET 2.0 project, and in C# 2 there is no "var" keyword.
Actually, a new class was generated:

image

But, this class is hidden with DebuggerHiddenAttribute and DebuggerDisplayAttribute so, in the debugging we can't see it.

And again, we see how we can use .NET 3.5 feature and C# 3 keyword in .NET 2.0 project under Visual Studio 2008. It's possible just because this (and everything else we see in this post) is a compiler trick, which doesn't requied any additional assemblies or features - and use CLR v2.0.

Extension Methods
Daniel Moth wrote about using Extension Methods in .NET 2.0 here.

Summary

Visual Studio 2008 support Multi Targeting which give us the option to develop .NET 2.0 project in VS 2008 and compile it with new version of the compiler. this compiler create a regular .NET 2.0 code - but give us the option to use .NET 3.5 and C# 3 features, that are actually compiler-tricks to work easily.
Behind the scenes, the compiler generate regular .NET 2.0 code.

Shahar.

Comments

Ohad Aston - ASP.NET Blog said:

Nice! u have blog in asp.net:)

# January 28, 2008 3:43 PM

shahargs said:

Yes, they now open the community for new members.

shahar.

# January 28, 2008 11:46 PM

Rob Philpott said:

Helpful bit of info that. Good work!

# July 24, 2008 4:50 AM

Brendan said:

Does anybody know of a way to turn this feature off so these will cause errors in projects building off the .net 2.0 framework?  I understand it works find when building through VS2008 but when our continuous integration server tries to build these using the command line, the build just breaks and then we have to go back and find these to fix them.  It would be nice to have them error out locally in Visual Studio before we can check in the code.

# November 5, 2008 3:03 PM

Ojulari Hakeem said:

One thing I undesrtand with using a variant keyword is it prompts runtime error when there type mismatch. That is why it was introduced initially in .NET framework. Now that var is introduced how could runtime error be avoided?

# March 30, 2009 4:29 AM

baby shower ideas said:

i'm glad that i have .NET 3.5 because it's a lot easier to use - though these tips certainly look helpful for those still using the earlier version of the software.

# December 1, 2009 3:28 AM

Traverse City Hotels said:

The Extension Methods in .NET 2.0 article was really useful. Helped me a lot great link. Thanks

# July 28, 2010 11:54 PM

must have ipad accessories said:

Sow nothing, reap nothing.

-----------------------------------

# December 20, 2010 2:11 AM

ipad app review said:

Good is good, but better carries it.

-----------------------------------

# December 24, 2010 12:20 PM

ipad stand said:

-----------------------------------------------------------

I have been reading your posts in the course of my smoke break, and I've to confess the whole article has been really informative and extremely properly written. I thought I would let you know that for some cause this website does not show well in IE 8. I wish Microsoft would cease upgrading stuff. I have a query for you. Would you thoughts swapping blog roll links? That would be genuinely neat!

# January 2, 2011 6:46 PM

Kurtis Halcom said:

Extremely nice post. I just stumbled upon your blog and wanted to say that I've seriously enjoyed surfing around your blog posts. Immediately after all I will be subscribing to your rss feed and I hope you write again soon!

# July 4, 2011 9:25 PM

tryecrot said:

Yes there should realize the opportunity to RSS commentary, quite simply, CMS is another on the blog.

# August 28, 2011 5:50 AM

plan b online said:

I’m really loving the contents of your blog. Hopefully you keep posting regularly. Thanks.

# August 28, 2011 1:44 PM

seroquel said:

Thanks for tris interesting information! I found it very useful =)

# September 4, 2011 10:05 PM

Bella Rossi said:

This information was very useful.

# March 24, 2012 8:12 PM

www.topsunglassesholidays.com said:

Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You definitely know what youre talking about, why waste your intelligence on just posting videos to your weblog when you could be giving us something enlightening to read?

# August 25, 2012 5:28 AM

Troy said:

Thanks for the good writeup. It in truth was once a amusement account it.

Look complex to far added agreeable from you! By the way,

how could we be in contact?

# April 11, 2013 11:45 AM

http://seekingalpha.com/user/11604121/profile said:

Don't worry if it doesn't have grain, as they are not really necessary in a pet's eating plan, but above all else, avoid getting processed items which contain filler injections like maize and grain. These filler injections are only good for bulking out the meals (and your cat); it has no health benefit.

# May 2, 2013 8:08 AM