This is my personal blog. The views expressed on these pages are mine alone and not those of my employer.

Monday, 15 September 2014

Pretentious Parameters and the C# Compiler

I was reading through Jon Skeet's brilliant C# In Depth when I came across a thought provoking shred of info tucked away in Part 4.

Jon was describing optional parameters, how they've been supported in the CLR from .NET 1.0 and the motivation behind their inclusion in C# 4. Along with this he provided an example which exhibits behaviour you probably won't expect.

First create a class library in which you define an optional parameter:

then reference it from a separate project:

Fire up your favourite IL decompiler and take a look at Program

Program has taken the value 20 directly from LibraryDemo and assimilated it as it's own. What the hell?

I'm sure you're already picturing the issues this can lead to.  If you were to modify LibraryDemo and neglect to recompile Program you will still get 20, which, believe me, will lead to bugs that are damn hard to track down.

This does at least explain why the requirements for optional parameters are as so:
The expression in a default-argument must be one of the following:
  • a constant-expression 
  • a new expression of the form new S() where S is a value type
  • an expression of the form default(S) where S is a value type
All of these expressions are known at compile time allowing the compiler to stuff whatever you specify into other classes / projects / trash can.

However the reality is we don't care what the compiler is doing, since this is an example of an implementation detail, of which I've already taught you not to rely on. Therefore I'm quite happy to place this as a simple curiosity, which may well help save a colleagues sanity in the near-future.

...and anyway, when do you ever build a single project without building the whole solution?