C# Params

In C#, the Params keyword is employed to specify a parameter that can take in a flexible number of arguments. This keyword holds significance within the C# language as it facilitates invoking a method with an indefinite number of arguments without the need to manually create an array. Moreover, it grants a method the capability to receive varying arguments of a particular data type, and it is essential to utilize it with a Single-dimensional array.

Params Example in C#

Let's consider a scenario to demonstrate the Params keyword in C#.

Example

Example

using System;

namespace AccessSpecifiers

{

    class Program

    {

        // define a method for integers

        public void Show(params int[] num_bers)

        {

            Console.WriteLine("The integer values are ");

            foreach (int num1 in num_bers)

            {

                Console.WriteLine(num1);

            }

        }

        // create a method for strings

        public void Show(params string[] messages)

        {

            Console.WriteLine("The String values are ");

            foreach (string msg in messages)

            {

                Console.WriteLine(msg);

            }

        }

        static void Main(string[] args)

        {

            Program p1 = new Program();

            // Call with integer values

            p1.Show(1, 2, 3, 4, 5);

            // method call with string

            p1.Show("Hello", "World", "C#", "Params");

        }

    }

}

Output:

Output

The integer values are

1

2

3

4

5

The String values are

Hello

World

C#

Params

Explanation:

In this illustration, we showcase the process of declaring the Params keyword in C#. Initially, we establish a pair of functions: one that accepts a variable number of integers, and another that accepts a variable number of strings. Within the main function, we instantiate an object of the Program class and invoke the Show method. Subsequently, we employ the Console.WriteLine method to display the result.

Using the params Keyword for Variable Number of Arguments in C#

Let's consider a scenario to demonstrate the utilization of the params keyword for handling a variable number of arguments in C#.

Example

Example

using System;  

namespace AccessSpecifiers  

{  	

    class Program  

    {  

        // define a method for object

        public void DisplayItems(params object[] items)   

        {  

            for ( int i = 0; i < items.Length; i++ )  

            {  

                Console.WriteLine( items[i] );  

            }     

        }  

        // Main function, execution entry point of the program  

        static void Main(string[] args)  

        {  

            Program p = new Program(); 

            p.DisplayItems("Krishna", "John", 11, 20.5, "Peter", 'X'); // Passing arguments of variable length  

        }     

    }  

}

Output:

Output

Krishna

John

11

20.5

Peter

X

Explanation:

In this instance, we illustrate the utilization of params for handling a flexible count of arguments. Initially, we establish a function called ShowItems which can take multiple arguments of diverse types. Subsequently, we employ a for loop to cycle through each element in the array and display it using the Console.WriteLine method. Within the main function, we instantiate an instance of the program class and invoke the ShowItems function.

Program to add the element of an array passed to the method in C#

Let's consider an instance to demonstrate the process of appending an item from an array that is supplied to the function in C#.

Example

Example

using System;	

class tech

{

    // create a method using params 

    public static int Sum(params int[] numbers)

    {

        int sum1 = 0;

        // Loop through each number and add to sum

        foreach (int num in numbers)

        {

            sum1 += num;

        }

        return sum1;

    }

    // Main Method

    static void Main(string[] args)

    {

        // Calling the method with different numbers

        int result = Sum(10, 20, 30, 40, 50);



        // Display the outcome

        Console.WriteLine("The total sum of the given numbers is " + result);

    }

}

Output:

Output

The total sum of the given numbers is 150

Explanation:

In this instance, a function called Total is established to accept multiple integer parameters. Subsequently, an iteration loop is employed to compute the total of the specified integers. Within the primary function, Total is invoked with a set of five integer inputs (10, 20, 30, 40, 50). Ultimately, the result is exhibited by utilizing the Console.WriteLine method.

Why use the params Keyword in C#?

In C#, the params keyword is primarily used to specify a parameter that can take a flexible number of arguments. Rather than having numerous overloaded methods for distinct parameters, we can establish a solitary method that can manage any quantity of inputs seamlessly. This approach enhances the clarity and sustainability of the code by allowing the passing of an array as an argument.

Rules for Creating the Params in C#

There are several rules that help to create the params in C#. Some of them are as follows:

  • Only one params parameter allowed: We can use only one parameter in a method, and it must appear at the end.
  • Must be a Single-Dimensional Array: It must be a single-dimensional array, and all arguments passed to it must match the specified array type.
  • Empty array: If no arguments are passed to the parameters, it will be treated as an empty array.
  • Benefits of Params in C#

Several benefits of params in C# are as follows:

  • Simplifies Method Overloading: Without params, we have to create multiple overloaded methods to handle different numbers of arguments. If we are using params, it enables us to write a single method that can accept a variable number of arguments, which makes the code simpler and more maintainable.
  • Support Implicit Array: When we are using params, the compiler automatically wraps the provided arguments as an array. So, there is no requirement to create it explicitly.
  • Flexibility: The param keyword provides flexibility in C#. We can pass zero or multiple arguments to the method. It acts as an optional array parameter.
  • Improved Readability: The params keyword helps us to avoid the many versions of the same methods for different numbers of inputs. Instead of creating multiple methods, we can write only one method using params, which automatically handles any number of arguments passed to it.
  • Conclusion

In summary, the params keyword plays a crucial role in developing functions for software development. It permits invoking a method with an unspecified number of arguments without the need to manually create an array, and enables a method to receive a varying quantity of arguments with specific data types. This feature enhances code flexibility, readability, and removes the necessity for method overloading based on parameter count.

C# Params FAQs

1) What is the params keyword in C#?

In C# development, the Params keyword is employed to specify a parameter that can receive a flexible quantity of arguments. This feature facilitates invoking a function with no arguments or multiple arguments without the need to manually create an array. Additionally, it permits a function to handle a variable number of arguments with a defined data type. The Params keyword is exclusively applicable in the context of a Single-dimensional array.

2) How many params parameters can a method have?

In C#, each method can only contain a single params parameter.

3) Can params accept different data types?

No, a params array must adhere to a singular specified type. In scenarios where there is a requirement to transmit varying types, the param object can be employed, enabling a mixture of types.

4) Do we need to provide arguments for a params method in C#?

No, supplying arguments to a params method is not mandatory.

Example

PrintValues(); // valid call

5) Can we pass an array to a params method in C#?

Yes, we can pass the array to a params method.

Example

PrintValues( 1, 2, 3 );

PrintValues(new int [] { 1, 2, 3 });

Input Required

This code uses input(). Please provide values below: