Monday, August 24, 2009

Named and Optional Arguments

One of the interesting feature of C # 4.0 is to have the Named and Optional Arguments, Optional Argument gives the flexibility of omitting the parameters in the call, and Named Argument gives the flexibility of passing the arguments by name in place of position.

Named Argument:
It provides us the flexibility or positioning the parameters by name in place of position, the value can be be provided by the use of argument. Lets see an example

student s = new student(name : "Ram", age : 25)

Optional Argument:
Any call for the function having the Optional Arguments have to specify only the required argument and can omit the optional arguments. Each of the Optional argument must have the default value assigned so that that value can be used when the value is not provided in the method call.

Method definition
void getClass (string Name, int age=20) (…)
Method Call
s.getClass(“Ram”);

When we invoke the method above it will pass Name as the parameter provided in the method call and the default value of age will be used.

Now let us consider the overloaded methods
void getClass (string Name, int age=20) (…)
void getClass (object o) (…)
void getClass (int age , string name = “Ram”) (…)
void getClass (int age) (…)

and if we call
s.getClass(4);

In the above overloaded functions the function getClass (string Name, int age=20) cannot be called as the parameter are not matching so remaining 3 are the better bet, in the remaining 3 converting the value 4 to int is better than converting to object.Among the last two overloaded functions, signature of the method getClass(int age) matches exactly to the call due to which the optional argument method will get lower priority and method getClass(int age) will be called.

No comments:

Post a Comment