Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Pretentious Parameters and the C# Compiler

4.95/5 (4 votes)
6 Mar 2015CPOL2 min read 6.4K  
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 information 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:

C#
public class LibraryDemo
    {
        public static void PrintValue(int value = 20)
        {
            System.Console.WriteLine(value);
        }
    }

Then, reference it from a separate project:

C#
class Program
    {
        static void Main(string[] args)
        {
            LibraryDemo.PrintValue();
            Console.ReadLine();
        }
    }

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

Image 1

 

Program has taken the value 20 directly from LibraryDemo and assimilated it as its 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 follows:

10.6.1

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 colleague's sanity in the near-future.

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

Image 2

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)