The params keyword in C# lets developers pass any number of arguments to a method, making it easier to work with lists or arrays. It was first introduced in C# 1.0 and is still useful today. This blog will dive into the new feature in C# 13 related to params usage
Prerequisites
- Visual Studio 2022 – 17.12 version
- .NET 9.0
You can download the Visual Studio Community edition from here.
What is param collection?
The params keyword in C# lets a method take a flexible number of arguments as a single parameter, usually as an array. When a parameter is marked with params, the caller can pass either individual values or an array. This makes it easier to call the method, especially when dealing with optional or unknown numbers of values.
For instance
void PrintParamsWithArray(params int[] numbers)
{
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
//The usage would be:
PrintParamsWithArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
C#
Copy
Before C# 13, the params keyword could only be used with arrays. However, with this new feature, you can now use params with any collection type.
The recognized collection types are given below.
System.Span<T>, System.ReadOnlySpan<T>, and types that implement System.Collections.Generic.IEnumerable<T> and have an Add method. You can also use interfaces like System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IList<T>, not just specific types.
Please refer to the Microsoft learning document for more details.
Let us look at an example.
The source code can be downloaded from GitHub.
Use List with params.
internal static class WithList
{
public static void Display(params List<int> numbers)
{
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
}
// Usage
Console.WriteLine("Params with List");
WithList.Display([1, 2, 3, 4, 5, 6, 7]);
C#
Copy
Use Span with params.
public static void Display(params ReadOnlySpan<int> numbers)
{
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
// Usage:
Console.WriteLine("Params with Span");
WithSpan.Display(1, 2, 3, 4, 5);
C#
Copy
Let’s run the program, and you’ll see the following output.
The params keyword in C# is a useful tool for managing variable numbers of arguments. Since it was introduced in C# 1.0, it has helped developers write cleaner and more flexible code by making it easier to pass multiple parameters to methods.
Happy Coding!