Sunday, December 30, 2007

Word + Blogger + HTML = Bad idea!

A quick post-post: The previous post was written in Microsoft Word 2007, and published through the same. I spent more time fixing layout errors and HTML stuff than writing :-(

How to make the compiler do your work

Before Christmas I spent a few weeks on a school project in computer science. The choice of technology was up to us, and I naturally took the safe path of .NET and C#. I used Visual Studio 2008 as IDE, as it had just come out, and I wanted to try it out. I also wanted to test C# 3.0, which the new IDE of course facilitated. Later I came to think that my team and I wanted to have the solution running on a web server, so the examiners would be able to see the actual prototype working. As I didn't have any options for running the prototype on a .NET 3.5 server, I had no choice but to make the solution .NET 3.0 compatible. This is no big thing in Visual Studio 2008 – you just change the target framework and recompile. Naturally a lot of compiler errors emerged. But to my surprise, they were all related to references to .NET 3.5 specific assemblies, and not my actual code! This got me thinking, and investigating.

I used "simple properties", which is an easier way of writing simple properties with no get/set logic, other than setting a backing field's value or returning it, a lot. When you write them in C#, it looks like this:

Simple properties

What happens when above is built is that the compiler generates the get_Id() and set_Id(int value) methods as before, but then also generates a backing field that reverse engineered looks something like this:

Backing field

The funny thing is the naming of the generated field. Note the < and > symbols; they are used in order to avoid C# code accessing the field! If I try to get access to the field from a C# method, I will get a compiler error, as < and > are not allowed in the context.

The full property will look like this after being compiled:

Compiled property


I never thought of this, but as all the features of C# 3.0 are "syntactic sugar" changing the target framework while keeping the C# 3.0 compiler, I can have all the features, even though everything is compiled to C# 2.0! Great!

Oh, and by the way: Note the [CompilerGenerated] attribute. I want all of my compiled code to have that!