Monday, November 3, 2008

The "var" keyword works in .NET 2.0?

Just the other day I installed Resharper 4.1 into my copy of Visual Studio 2008. Once I loaded my .NET 2.0 web application Resharper started suggesting I replace my variable type declarations with "var"!

What's this? Isn't "var" a C# 3.0 (.NET 3.5 Framework) feature?

So for giggles I swapped int for var and did a solution build (Ctrl + Shift + B).

NO ERRORS!

I ran the web application.

NO ERRORS!

So I posed a question to my twitter friends.

Why is my C# project for 2.0 framework, compiling fine with "var"?

Turns out, it's all Visual Studio 2008 slight of hand. As Phil Japikse says:

@JustinKohnen it's syntactic sugar in VS2008. If you look at the IL, it compiles down to 2.0 compatible code.

Isn't that interesting? You can also use automatic properties, and object initializers too! After Phil opened my eyes, he wrote a great blog post about these Visual Studio 2008 Compiler Tricks.

A thanks to Phil Japikse, Leon, and Matt Brewer for the help.