Thursday, July 2, 2009

Visual Studio 2008 var Keyword ‘Bug’

I stumbled across an interesting bug while editing an ASP.NET web project in Visual Studio 2008 a few days ago and I figure after four years of using the Visual Studio suite without encountering any real bugs, one isn't all that bad. That being said, given the nature of the behavior I encountered, I was compelled to investigate the issue behind it.

With the introduction of C# 3.0's implicit variable keyword var Microsoft added some simple tricks to the compiler in order to produce the traditional C# 2.0 IL code backing this new keyword. That being so, .NET 2.0 projects are fully capable of running projects written with most C# 3.0 syntax.

The bug I encountered, if you can call it that, pertains to how Visual Studio treats code written inside ASP script tags within the page markup. As has been the case since classic ASP, C# or VB code can be written directly into the markup using <% %> tags. Consider the following rudimentary example:

<%
  string hello = "Hello";
  Response.Write(hello);
%>

Like code placed in your code behind, this code is run when the page is loaded by the user; unlike the code in your code behind, this code is not compiled until runtime. A key distinction.

This brings me to the bug I noticed in the editor that pertains more to syntax highlighting than anything else. Consider this identical example written with C# 3.0 syntax.

<%
  var hello = "Hello";
  Response.Write(hello);
%>

Functionally these two blocks of code perform the same task and produce the same IL code when compiled; however, running the latter piece of code in a .NET 3.5 project will not yield the same results as it does in a .NET 2.0 project. Due to the fact that code contained in script tags is not compiled until runtime the target environment ultimately affects the compilation of that code. For that reason, given that the .NET 2.0 runtime doesn’t know what var means it cannot correctly detect the type and compile the code.

Now this behavior is neither surprising nor a bug in itself, but rather it pertains to small lack of gracefulness on Visual Studio’s part in detecting this specific condition. In Visual Studio 2008 while editing a C# project var is a keyword that is highlighted by the editor regardless of the target platform because in all but this one scenario var can safely be used in a .NET 2.0 project and, unfortunately, the development team overlooked this one scenario.

One more thing worth noting for all you ReSharper users out there is the breaking vulnerability this exposes with the Code Cleanup tool in the plug-in. If you have ever tried configuring the Code Cleanup options you may have noticed it is possible to tell it to replace all explicit variable definitions with the implicit var keyword. If you’re running a .NET 2.0 project with inline script tags in your pages make sure to watch for this setting and ignore the inline code inspection advice.

Happy Coding!

No comments: