Default, Optional & Named Parameters Usage

1. In modern days, using default/optional/naming parameters we can use method overloading concept. Really interesting one. It reduces long list of methods in our code file if we go for earlier method overloading concept.

2. Required parameters should be placed before the optional parameters in the method definition and method calling. Else we get compiler error.
#right way (FIG : I)

private void Super(int calculatedPoints,string status=”success”)
{

}

Here, calculatedPoints is the required parameter and status is the optional parameter. you can not define the method like below

#Wrong way

private void Super(string status=”success”, int calculatedPoints)
{

}

Eg:

private void Super(string one=”Srini”,string two=”Nice”)
{

}

I would like to give you quick explanation about Default/Optional/Naming parameters. Let’s get into that.

Default Parameters

If we call the below method, output will be

* Super();   // srini and Nice will be taken as values.

Named parameters

* When you have multiple number of same data types passing to the method, Make sure to specify the parameter name along with value, like below

Super(one:”self”,two:”confidence”); //If you didn’t specify the “one” parameter, the complier will get confused to which of the parameter that value to be passed.

If your method don’t have same data types, then you just simply pass the value. that’s enough.

Optional Parameters

* Super(one:”Self”); you can call the method without passing the value for another parameter, two will have the value as default “Nice“.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: