Thursday 15 March 2012

C# Optional Arguments Gotcha

I came across an interesting quirk of C#'s optional arguments when coding a MVC site against my Linq2Sql BLL. The BLL handles all my database logic including the creation of the Linq DataContext. In some edge cases I need to recycle an existing DataContext; so I made the DataContext an optional parameter. All good until I instantiated a new instance of the BLL in my shiny new MVC website - new BLL() - and encountered this error:

Error 11 The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced.

Apparently the calling code must know about the optional object type even when it's not specified. After some googling it looks like the optional parameters are baked directly into the IL at compile time. It wouldn't make sense to do this on the callee side, so this seems very odd behaviour.