C# 4 new features ~ Basic method invocation changes - Optional and Named parameters

(This post is part of my Visual Studio 2010 series)

C# 4 brings many new features, couple of them are optional parameters and named parameters. If you have used Visual Basic, you know these features are already available in VB. Adding these to C# makes it even better and helps C# coders who are from visual basic.

Optional parameters

Optional parameters allows you to create methods with default values for some parameters, so that you can ignore passing values to them.

Like..

public string ReadFile(string FileName = "Defaultfile.xml")
{
..
}

..

string str1;
str1 = ReadFile(); //optional parameter ignored

string str2;
str2 = ReadFile("Orders.xml");

You have to specify a value to the optional parameter in function definition as above, this will be used if you don’t supply a value while calling the method. Quick info(Ctrl+I) helps more by showing the optional parameter’s default value.

Until C# 3, we had to create unnecessary method overloads if we have to avoid some of the parameters of a method for simplification, instead, now we can specify a default value and code the method appropriately.

If you are an architect you must make use of these effectively, so that it is even easier to use your code libraries, architecture, etc.

Named parameters

Named parameters allows you to pass values to functions by specifying the parameter names in function call itself.

Like..

public string SearchProducts(string ProductID, string ProductName, string Category)
{
..
}
..
SearchProducts(ProductID: "A020", ProductName: "mvc", Category: "asp.net");

Even though using this style everytime isn’t practical, if you like to improve clarity and readability of specific method calls you can use this.

Because, instead of..

SearchProducts("A020", "mvc", "asp.net");

Named parameters tell what each parameter is for.

 

If you too have a special scenario where these could be used, please put it in comments..

Bookmark / Share

Comments for this entry..

Super! Very interesting!

by.. Oleg | February 16, 2010 14:30 | Reply

C# 4 new features ~ Basic method invocation changes - Optional and Named parameters

C# 4 new features ~ Basic method invocation changes - Optional and Named parameters

by.. CodeHappiness.com | July 17, 2010 21:36 | Reply

Write your comment..




biuquote
  • Comment
  • Preview
Loading