With C# 4.0 you can assign a default value to a parameter when you are declaring a method

e.g.
public static void updateMyCV(string name=”Dhanushka”){ do some task }

you can call the method in following ways
updateMyCV(); //this will assign the default value to the parameter name
updateMyCV(“Athukorala”); //passed in value is assigned to the parameter

As you can see when you are calling these method, parameters in the method becomes optional. We can use this feature coupled with named parameters to define methods with an optional set of parameters.

e.g.
public static void
updateMyCV
(int employeeID, string firstName=”Dhanushka”, string lastName=”Athukorala”)
{ do some task }

When you are declaring a method with optional parameters, required parameters need to come first before any optional parameter declaration, here parameters with default values are considered as optional parameters while others are considered as required. There are several ways to call this method legally.

e.g.


updateMyCV(155,”Tekla”,”Dilrukshi”);
updateMyCV(155,”Tekla”);
updateMyCV(155,lastName: “Dilrukshi”);
updateMyCV(155);


But you cannot call the method in following ways although it makes sense to do so

updateMyCV(); //required parameters need to be passed
updateMyCV(155, ,”Dilrukshi”); //cannot leave gaps between arguments
updateMyCV(“Dilrukshi”,155);
//order has to be maintained if you are not using named arguments in the method call

0 comments:

Post a Comment