Tuesday, 3 December 2024

What is Params In C#?

Leave a Comment

When working with methods that accept a variable number of the same type of parameters, the "params" keyword is essential for increasing flexibility and ease in C# programming.


C# parameters

This feature, which enables developers to send an arbitrary number of parameters or optional parameters of the same type in a method declaration, is especially helpful when the precise number of arguments is unknown in advance.

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.

 Now, add the code below.

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.


 

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

0 comments:

Post a Comment