Passing Arguments in Parameterized Methods in a Different Way

Passing Arguments in Parameterized Methods in a Different Way :

Suppose, if we have a Method like,

public void MyMethod (int firstValue, double secondValue=3.14,

string thirdValue= ”My ThirdParameter”)
{
     ---------
    (your code here)
    ---------
}

If we want to call it and wanted to specify the First and the Third Parameter but not the Second.

You are wondering should we do this? Is it possible?

Yes it is, no problem at all, we can do this.

We can do so by using the names of the parameter such as

MyMethod(10, thirdValue: ”My New Parameter”);

In the above code we passed only two Arguments to our Method which actually accepts three Parameters, now the question is that then How does the above code works?

As we are passing the first argument of the integer type viz 10, our Method accepts the first parameter as integer. Now we can see that our second parameter is constant and if we don’t want to change it, then there is no any need of any extra efforts to again pass the same value from calling Method. It is only required to pass the 3rd argument. For this we have to just write the name of the the 3rd Parameter which we declare in our Method definition, and pass the value separated by ‘:’. But make sure that it matches the type of that Parameter. Using this way you can pass arguments of any no. of parameters, there isn't any worry about the order of passing it.

This flexibility is actually added in C#4.0. Before this version the only option we had was to overload the Method.