Using the `params` Keyword in C#: Creating Methods with Variable Arguments

Learn how to create flexible and adaptable methods in C# that can accept a variable number of arguments using the `params` keyword. This tutorial explains the syntax, demonstrates its usage with different data types, and highlights its benefits in creating reusable and versatile methods.



Using `params` Keyword for Variable Arguments in C#

Understanding the `params` Keyword

In C#, the `params` keyword is used to create methods that can accept a variable number of arguments. This is particularly helpful when you don't know beforehand how many arguments a method needs. The `params` keyword is used in the method signature to declare a parameter that accepts an array of values. This means the method can be called with any number of arguments of the specified type, allowing for flexibility in how methods are called. The arguments are passed as an array to the method. Only one `params` keyword can be used in a method's parameter list, and it must be the last parameter.

`params` Keyword Syntax

The syntax is:

public void MyMethod(params int[] numbers) { ... }

In this example, the `numbers` parameter is a `params` parameter that takes an array of integers.

Example 1: Variable Number of Integers

This example demonstrates using `params` to pass a variable number of integer arguments. The method iterates through the array and prints each value.

C# Code

using System;

public class ParamsExample {
    public void Show(params int[] numbers) {
        foreach (int number in numbers) {
            Console.WriteLine(number);
        }
    }

    public static void Main(string[] args) {
        ParamsExample example = new ParamsExample();
        example.Show(1,2,3,4,5);
    }
}

Example 2: Variable Number of Objects

This example demonstrates using `params` with `object[]`, enabling the passing of a variable number of arguments of different types.

C# Code

using System;

public class ParamsExample {
    public void Show(params object[] items) {
        foreach (object item in items) {
            Console.WriteLine(item);
        }
    }

    public static void Main(string[] args) {
        ParamsExample example = new ParamsExample();
        example.Show("one", 2, true, 3.14);
    }
}

Conclusion

The `params` keyword is a valuable tool in C#, providing flexibility in method design. It simplifies the creation of methods that can accept varying numbers of arguments, enhancing code reusability and reducing code duplication.