advanced web statistics

Utilize the var Keyword While Targeting 2.0 Applications

12/29/2007 4:05:09 AM

Today while giving a brain-dump for a project I am no longer working on I learned something new about 2008 and targeting the 2.0 Framework.  For those of you that don't know, with 2008 and .NET 3.0 Framework there is a new var keyword.  Using this keyword you can still have type-inference (strongly-typed).

So if you convert a 2005 website to 2008 you can replace code like this:

public static List<SqlParameter> CreateParameters(object input)
{
   List<SqlParameter> parameters = new List<SqlParameter>();

   foreach (PropertyInfo p in input.GetType().GetProperties())
      parameters.Add(new SqlParameter(p.Name, p.GetValue(input, null)));

   return parameters;

With code like this:

public static List<SqlParameter> CreateParameters(object input)
{
   var parameters = new List<SqlParameter>(); // !practical, but works

   foreach (var p in input.GetType().GetProperties())
      parameters.Add(new SqlParameter(p.Name, p.GetValue(input, null)));

   return parameters;

I think it's cool. Not as long-winded. Especially if you have code like this:

Dictionary<List<Foo>, Dictionary<Data, List<Bar>>> d = new Dictionary<List<Foo>, Dictionary<Data, List<Bar>>>(); 

You can now write it like this:

var d = new Dictionary<List<Foo>, Dictionary<Data, List<Bar>>>();

There is kind of a gotcha if you decide to utilize this keyword in your 2.0 projects.  If you are like me and utilize Web Application Projects then you probably have your POCO's (Plain 'Ole CLR Objects*) in an App_Code folder. The issue is that your project will compile successfully but when you F5 / CTRL + F5 you will get an error.

var error

We found today that to rectify this problem you simply need to rename your App_Code folder to something like _code or _App_Code (what I did).  You can compile your project and deploy with no problems without renaming this directory but you won't be able to test locally. The code in your App_Code directory will compile dynamically thus rendering using the cool keyword useless.  If you simply reference separate class libraries for Business Logic and Data Access this should be a non-issue.

* I forgot where I originally found this term to refer to ADO.NET Generated classes but it stuck with me.  I think it was when I was learning the fundamentals of NHibernate.

UPDATE
Some people like var. Other's don't.  I like to use var for cases such as Andrew describes (see comments) but I know that others that don't like to type as much / lazy like to use it as a shortcut.

C#, Orcas

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!