Multiplay Labs

tech hits and tips from Multiplay

Archive for the ‘optional parameters’ tag

When optional method parameters aren’t optional in C#

without comments

So csharp added optional parameters in C# 4.0 which is great no more adding loads of method signatures when you want to add an additional parameter to an existing method, or so I thought.

While working on TShock I used optional parameters to extend the functionality of existing methods in the core API, to my surprised I started seeing reports of existing plugins failing with missing method exceptions. After some investigation I discovered that the way C# implements optional parameters is it bakes the defaults into the caller and not into the callee.

The result of this is that until all existing code is recompiled against the updated API, it will fail to run. Not only this but if you update the defaults values of your optional parameters then again all code must be recompiled, not just that containing the update, to ensure the new values are always used.

Clearly this is a PITA for public API’s so wanted to mention it so others are aware of this significant gotcha with optional parameters in csharp.

Written by Dilbert

March 3rd, 2012 at 4:19 pm

Posted in CSharp

Tagged with , ,