What is Params In C#?

C# Params

In C# programming, the "params" keyword plays a crucial role in enhancing flexibility and convenience when dealing with methods that accept a variable number of the same type of parameters.

C# Param arguments

This feature is particularly useful when the exact number of arguments isn't known beforehand, allowing developers to pass an arbitrary number of parameters or optional parameters of the same type in a method declaration.

class Program
{
    public static void AddItemsToShoppingBasket(params string[] items)
    {
        // ....
    }

    public static void AddItemsSumToShoppingBasket(params int[] sum)
    {
        // ....
    }
}

Here, we do not know the count of items beforehand, and the method is written in such a way by specifying the params keyword that it accepts string items without specifying the count.

The params keyword is employed in this method signature declarations to denote that a parameter array can be passed to the method. This array can hold zero or more values of a specified type and can also be an optional parameter/hold optional arguments.

The default value for this parameter is an empty array of the type specified in the method signature. For example, when a method containing the argument 'params object[] objects' is called without any parameters, it creates an empty array of objects.

As shown below, "AddToShoppingBasket" can be invoked with a variable number of arguments of string parameters. The params keyword simplifies the syntax for the method call by allowing developers to pass the optional parameters directly without explicitly creating an array.

class Program 
{
    AddItemsToShoppingBasket("cake", "pizza", "cold drink");
    AddItemsToShoppingBasket("snacks", "burger");
    AddItemsToShoppingBasket(); // Valid with zero parameters
}

Considerations and Best Practices

Now that we have introduced the params keyword in general let us dive deep into some considerations and best practices of the 'params' keyword.

The parameter type must be a one-dimensional array.

To use the params keyword specified in the method "AddItemsToShoppingBasket" defined above, we can pass a one-dimensional array instead of manually calling the method using parameters like below.

// example

class Program 
{
    var items = [] {"cake", "pizza", "cold drink"}; // one-dimensional string array
    AddItemsToShoppingBasket(items); // works
    AddItemsToShoppingBasket("cake", "pizza", "cold drink"); // same as above line

}

Can pass a comma-separated list of arguments for the type of the array elements.

While using a method with the params keyword, we can pass multiple values of arguments as comma-separated values.

// example method signature

class Program 
{
    AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // comma separated values
    AddItemsToShoppingBasket("snacks");
}

Pass an array of arguments of the correct type

The below code throws an error if we try to add items of type int into the shopping basket.

// example

AddItemsToShoppingBasket("snacks",2,"burger"); // error
AddItemsToShoppingBasket(2,3,4); // error as params type is string

This occurs as the array argument is a string type and not an int type.

Params should be the last parameter in the Method

No additional parameters are permitted after the params parameter in a method signature declaration, and only one params argument is permitted in a method parameters declaration.

Params should be the last argument of the method signature. This means that all required parameters need to be specified before the params argument.

This is shown in the following code.

static void Main(string[] args)
{
    public static void AddItemsToShoppingBasket(decimal total, params string[] items)
    {
        // ....
    } // This works
}

static void Main(string[] args)
{
    public static void AddItemsToShoppingBasket(decimal total, int totalQuantity, params string[] items)
    {
        // ....
    } // This works
}

static void Main(string[] args)
{
    // Compiler error, This does not work as the params argument is declared before other arguments
    public static void AddItemsToShoppingBasket(params string[] items, decimal total, int totalQuantity)
    {
        // ....
    }
}

Only One params keyword.

There can only be one params parameter in a method signature.

class Program
{
    static void Main(string[] args)
    {
        public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
        {
            // Compiler error, This does not work.
        }
    }
}

You can pass no arguments.

If you send no arguments, the length of the params list is zero.

AddItemsToShoppingBasket(); // Works 

For any parameter with params, an argument is considered optional and can be called without passing parameters.

Code Example

Here is a complete code example written in C# that shows how to pass different numbers of variables in a params method as a params argument and read these values back in the caller code.

Create a new console application

In Visual Studio, select Create New Project to get the below window. Here, you can provide the Solution Name, Project Name, and paths. Once this information is entered, click next to create the console application ready to start coding.

Console application

Now, add the code below.

// See https://aka.ms/new-console-template for more information.

class Program
{
    List<string> cart = new List<string>();

    void AddItemsToShoppingBasket(params string[] items)
    {
        for (int i = 0; i < items.Length; i++)
        {
            cart.Add(items[i]);
        }
    }

    // caller code
    static void Main(string[] args)
    {
        Console.WriteLine("Params Example");

        Program program = new Program();

        Console.WriteLine("Enter the cart items as comma separated values");
        var itemsString = Console.ReadLine();

        if (itemsString != null)
        {
            var items = itemsString.Split(",").ToArray();
            program.AddItemsToShoppingBasket(items);
        }

        program.AddItemsToShoppingBasket("Sample1", "Sample2");

        Console.WriteLine("-------------------------------------------------------");
        Console.WriteLine("Display Cart");

        foreach (var item in program.cart)
        {
            Console.WriteLine(item);
        }
    }
}

Output

The output of the above code looks like the following.

Param example output

Conclusion

Params keyword is a versatile keyword in C# which simplifies programming to a great extent. As developers, knowing this keyword helps us easily develop apps in this modern-day development.