Tuesday, February 11, 2014

Named parameters revisited in .Net 4.5

As most of you are aware that there are lot of language and compiler changes has happened with recent release of .Net, but all the issues will not arise until and unless you are recompiling your code. Once you recompile your code, these changes will be introduced regardless of which framework you target.

Today I am writing about one of these breaking changes happened in .Net 4.5. 
With earlier framework, named and optional parameter concept was introduced and unfortunately it was implemented incorrectly. In essence, there was a issue with the evaluation order of named parameter and will occur only when you are using methods as an argument. 

Let's have a look at this snippet taken from MSDN:













Expected output: A C B
Output in Visual Studio 2010: C B A
Output in Visual Studio 2012/2013: A C B

Hope by this time, you are convinced about this incorrectness.  Please note, here issue is with named parameters and has nothing to do with optional parameters. This issue is with the Visual Studio 2010 compiler which is giving the unexpected results.

Reason: Incorrect results are because named parameters are evaluated before the positional arguments. For both named and positional evaluation must be from left to right. This was the bug in VS 2010 and is addressed in VS 2012.

This is unlikely to cause a problem in your code until and unless you are calling methods in your argument list.
Suggestion: Avoid calling methods in argument list if order of execution is important for your application.

Note: ref and out parameters may also suffer from side effects due to this change.

No comments:

Post a Comment