C# 4.0 Optional Parameters Explained

by silvercrux @ 21. May 2010 00:00

With release of the C# 4, the gap of features between VB.NET and C# just became narrower. C# 4.0 has introduced a new “Optional Parameters” support. So instead of explicitly passing in value for each variable in a method/constructor you can rely on default value defined in the method signature.

Let’s take a simple example :

 

public void AddPerson(string Name,int Age=30)
{
...
}

In this Example, now under C# 4.0, you can call this method as

 

AddPerson("Joe") //Age will implicitly be 30

 

Though theoretically this looks a nice shortcut, practical use of this may be discouraged. Adding an optional parameter to a public method that’s called from an external assembly requires recompilation of both assemblies – just as if the parameters were mandatory. This is so because this is just a syntactic sugar coat by the C# compiler. Behind the scenes C# compiler inserts code equivalent to AddPerson(“Joe”,30).

It is for this very reason optional parameters should be avoided in public methods that are supposedly going to be used by External assemblies.





© Copyright SilverCrux Technologies. All rights reserved. We provide website html services.