Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Passing Named Parameters in C# Functions

Dec 17, 2019 • 9 Minute Read

Introduction

Named parameters were introduced in C# 4 and have become quite popular because of the benefits and usability they provide over positional parameters.

In this guide, we will learn the following:

  • Named parameters and their key features
  • Using named parameters along with optional parameters

To illustrate this, we will be creating a program to call a function which calculates the volume of common 3D shapes such as cubes, spheres, cylinders, pyramids, and cones using named parameters.

Passing Parameters to Functions

First, let's review couple of examples of positional parameters and analyze why the position of the function parameters matter.

Example 1

Consider the below code, which calculates the volume of a cube when the length of the edge (side) is provided.

      double CalculateVolumeCube(double edge) {
     return Math.Pow(edge,3);
}

double Volume = calculateVolumeCube(5);
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 125.00
    

Example 2

Let's take another example of calculating a volume, but this time we are calculating the volume of a cylinder.

      double CalculateVolumeCylinder(double radius, double height) {
    return Math.PI*Math.Pow(radius,2)*height;
}

double Volume = calculateVolumeCylinder(2,4);
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 50.27
    

The above function takes radius and height as the parameters and returns the volume of the cylinder. When we provide the radius as 2 and height as 4, we get the volume as 50.27 (rounded up to two decimals). These are called positional parameters as the order in which the arguments are provided matter.

For further perspective, review the code below :

      double CalculateVolumeCylinder(double height, double radius) {
    return Math.PI*Math.Pow(radius,2)*height;
}

double Volume = calculateVolumeCylinder(2,4);
Console.WriteLine($"Volume: {Volume:N2}");
    

What do you think the answer would be? Will it be the same as Volume: 50.27?

      // Answer is Volume: 100.53
    

You might not be expecting this answer, but by closely looking at the function definition, we can see that the first parameter is height and not radius.

Typically, programmers waste a lot of time debugging this type of code because it does not provide a run time or compile time exception. The above function contained only two parameters, but imagine a scenario where we have a function with four, five, or more parameters. In this case, you must ensure that you review the function definition carefully each time you are passing arguments.

Passing Named Parameters to Functions

Now we will make changes to the above code and call the same function with named parameters.

      double CalculateVolumeCylinder(double height, double radius) {
    return Math.PI*Math.Pow(radius,2)*height;
}

double Volume = calculateVolumeCylinder(radius:2, height:4);
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 50.27
    

The above function calls give us the correct output, and there are two important things to consider:

  1. We did not make any change to the function definition.
  2. We did not follow the order of the arguments while calling the function. We provided the radius first and then the height.

What is a Named Parameter?

Put simply, named parameters provide you the option to associate the arguments that you have passed through a function to the parameter names rather than its position in the parameter list.

      // Function definition
void function(int param1, string param2, int param3) {}

// Valid function calls
function(12,param2:"Hello", 3);
function(param3:45, param1:34, param2:"Hello");

// Invalid function call
function(param3:45, param1:34, "Hello");
    

Rule: You can use named parameters along with positional parameters, but they should be in order. Out-of-order named parameters are valid only if they are not followed by positional parameters .

Example: Calculate Volume of 3D Shapes

Let's create a function that calculates the volume of the common 3D shapes and call it using named parameters.

  1. We will create an enum for the shapes.
      enum Shape {
        Cone,
        Cube,
        Cylinder,
        Pyramid,
        Sphere
    }
    
  1. Next we create a function which takes all the parameters along with the shape that we want the volume for.
      double CalculateVolume(double length, double width, double height, double radius, double edge, Shape shapeType)
    {
     double volumeResult=0.0;

        switch(shapeType) {
            case Shape.Cone:
                volumeResult = Math.PI*Math.Pow(radius,2)*(height/3);
                break;
            case Shape.Cube:
                volumeResult = Math.Pow(edge,3);
                break;
            case Shape.Cylinder:
                volumeResult = Math.PI*Math.Pow(radius,2)*height;
                break;
            case Shape.Pyramid:
                volumeResult = length*width*(height/3);
                break;
            case Shape.Sphere:
                volumeResult = 4*Math.PI*(Math.Pow(radius,3)/3);
                break;
        }
     return volumeResult;

    }
    
  1. We will then call the function with the shape that we want and provide the relevant values.
      // Calling the function by providing values through positional parameters.
Volume = CalculateVolume(0, 0, 0, 0, 5, Shape.Cube);
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 125.00

// Below examples use named parameters
// Volume of Cube 
Volume = CalculateVolume(edge:5, length:0, width:0, height:0, radius:0, shapeType:Shape.Cube);
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 125.00

// Volume of Cylinder
Volume = CalculateVolume(radius:2, height:4, length:0, width:0, edge:0, shapeType:Shape.Cylinder);
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 50.27

// Volume of Pyramid
Volume = CalculateVolume(length:2, width:3, height:4, radius:0, edge:0, shapeType: Shape.Pyramid);
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 8.00
    

The other benefit is that we just need to call a single function for volume calculation and not create separate functions for different shapes.

As with all the examples above, you can provide values to only the parameters that are required, and the order of the parameters doesn't matter, as long as positional parameters are not used.

Using Named Parameters With Optional Parameters

Using named parameters really simplifies things as we don’t have to worry about the order of parameters and we can specify the values for only those parameters that we want. When named parameters are used with optional parameters, the usability and the function call become easy and are much enhanced. Optional parameters are a way of saying that if you do not want to provide a value to a parameter, then we will take a default value and you can skip providing the value of that parameter during the function call.

There are two steps to this process:

  1. We must change our function definition to include optional parameters. The below function defines edge as 1 , shape as cube, and everything else as 0 .
      public double CalculateVolume(double length=0, double width=0, double height=0, double radius=0, double edge=1, Shape shapeType=Shape.Cube)
    
  1. We will then call the function with the shape that we want and only provide the basic values for us to calculate the volume of that shape.
      // Taking all the defaults
Volume = CalculateVolume();
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 1.00

// Volume of Cube
Volume = CalculateVolume(edge:5, shapeType:Shape.Cube);
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 125.00

// Volume of Cylinder
Volume = CalculateVolume(radius:2, height:4, shapeType:Shape.Cylinder);
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 50.27

// Volume of Pyramid
Volume = CalculateVolume(length:2, width:3, height:4, shapeType: Shape.Pyramid);
Console.WriteLine($"Volume: {Volume:N2}");
// Answer is Volume: 8.00
    

Rule: Optional parameters can only be defined at the end of the list, after all the required or named parameters (if any).

Conclusion

We now know what named parameters are and how they are used in functions. Remember, they might not be suitable for some scenarios but will mostly fit in whatever design pattern you are following. To summarize, named parameters are useful for a variety of reasons:

  • They free you from remembering the order of the parameters.
  • They improve the readability of your code.
  • They go along very well with optional arguments.
Ashish Minocha

Ashish M.

Ashish is a Technology Manager and architect with a deep passion for Cloud and been engaged with developing Cloud based solutions for Global Clients. He began his career with Windows NT and has done MCSE 2 times (now legacy) and he's Azure Architect certified. For many years, he worked on implementing Enterprise IP Telephony and deploying different CRM systems. He's had the privilege to work for different industries like Service, Manufacturing, Automotive and Banking. He loves understanding client business requirements and translating them into technology solutions. He also specialize in delivering POCs, escalation management, running pilots and managing technology projects. Teaching comes naturally to him as he started teaching university students when he was a student. Ashish is an advocate of MS Azure and has developed cloud Enterprise solutions specially for Emerging technologies like IOT, AR and Cognitive services. When he's not glued to his computer, he's either watching movies or playing video games.

More about this author