Optional and Named Parameters in C# - ProgramIdea

Optional and Named Parameters in C#


Optional Parameters

Optional parameters allow to omit parameters which have default value. For example, suppose we have a method Volume which has 3 parameter, length, width and height.

public double Volume(double length, double width, double height)
{
    return length * width * height;
}

Suppose you want to use this method for calculating volume by using fetures of optional parameter then this method written as : -

public double Volume(double length, double width, double  height = 10)
{
    return length * width * height;
}

then you can call this method when you supply all parameters

// supply all parameters
double volume = Volume(40, 50, 12);

another way to call this method by using Optional Parameter concept, if you are not supplying height parameter value then it will take default value which is defined that is 10.

// using feature of Optional Parameter
double volume = Volume(40, 50);

Named Parameters :

Named parameters allow you to supply parameters of method in any order, does not matter in which order their positions defined.

public double Volume(double length, double width, double height)
{
    return length * width * height;
}

then you can call this method by using Named Parameter feature by passing parameters in any order with parameter name and : operator as  

// using features of Named parameters
double vol = Volume(length: 40, width: 50, height: 12);

double vol = Volume(width: 50, height: 12, length: 40);

double vol = Volume(height: 12, width: 50, length: 40);