.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

C# 4.0 : Optional Parameters amd Named Arguments

Posted By:Baimey Rajesh       Posted Date: August 23, 2012    Points: 200    Category: C#    URL: http://www.dotnetspark.com  

A Preview of the C#4.0 feature Optional Parameters amd Named Arguments

Both Arguments and Parameters are Generally used in the same context. So, first Let Us see the difference between an Argument and Parameter


·          A parameter (also known as a formal parameter) is the variable that’s part of the method or indexer declaration.

·          An argument is an expression used when calling the method or indexer.

Optional Parameters

C# 4.0 supports using optional parameters with methods, constructors, and indexers 

To have an add function with different number of parameters, the only possibility in C#2.0 and 3.0 was method overloading

public int Add(int x, int y);
public int Add(int x, int y, int z);
public int Add(int w, int x, int y, int z);

But in C# 4.0 this is possible using Optional Parameters.

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions:

NB: All optional parameters must come after required parameters

public int Add(int w, int x, int y = 0, int z = 0);

since the default value of y and z are specified in the signature you can call this method as.

Add(1, 2); 
Add(1, 2, 3); 
Add(1, 2, 3, 4); 

  • ·          Optional parameters can’t have ref or out modifiers either.
  • ·          An optional parameter can be of any type, but there are restrictions on the default value specified
  • ·          There has to be an implicit conversion from the specified value to the parameter type, but this must not be a user-defined conversion.

Named Arguments

Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods.

The parameter for each argument can be specified by parameter name.

Consider a Function,

public void Add(int x, int y = 0);

This function can be used as

Add(y = 2, x = 1);

NB: Named Arguments with out and ref If you want to specify the name of an argument for a ref or out parameter, you put the ref or out modifier after the name, and before the argument. 

Hope things are clear.

Happy Coding :)



 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend