Optional Parameter in Csharp 4.0

Monday, October 19, 2009


Can i Use Optional Parameter in Csharp ? in 3.5 it was so difficult or impossible but Now Csharp i Mature language so Microsoft has introduced a new feature in C# 4.0 Called Optional Parameter . In this if we will not specify the value of parameter then function will automatically take default value rather then giving the compile time error. or

public void SendEMail(string toAddress, string bodyText, bool ccAdmin = true, bool isBodyHtml = false)
{
// Full implementation here
}

Least specified “overload” consuming code written will look like this:

SendEMail("jhon@foo.com", "Hello World");
The IL that the C# compiler will generate will actually be the equivalent of this:

SendEMail("jhon@foo.com", "Hello World", true, false);
The best part in this is that, unlike traditional method overloading, you have the ability to omit only the 3rd parameter in conjunction with the new Named Parameters language feature and write your code like this:

SendEMail("jhon@foo.com", "Hello World", isBodyHtml: true);
This will allow consuming code to only pass 3 arguments for succinctness but still invoke the appropriate overload since the IL generated in that instance will be equivalent to this:

SendEMail("jhon@foo.com", "Hello World", true, true);
share this post
Share to Facebook Share to Twitter Share to Google+ Share to Stumble Upon Share to Evernote Share to Blogger Share to Email Share to Yahoo Messenger More...

0 comments: