C# > Core C# > Methods and Parameters > params Keyword
Using 'params' for Flexible Argument Lists in C#
This code demonstrates how to use the params
keyword in C# to create methods that accept a variable number of arguments of the same type. This is useful when you don't know in advance how many arguments a method will need to process. The params
keyword allows you to pass either a comma-separated list of arguments or an array of arguments to the method. The method internally treats the arguments as an array.
Basic 'params' Keyword Usage
This example defines a method CalculateSum
that uses the params
keyword to accept a variable number of integer arguments. The arguments are treated as an integer array named numbers
within the method. The method iterates through the array, summing the values, and returns the total. The Main
method demonstrates how to call CalculateSum
with different numbers of arguments, including passing an array directly. It is crucial to check for null
, as the numbers
array will be null
if the method is called without arguments.
using System;
public class ParamsExample
{
public static int CalculateSum(params int[] numbers)
{
int sum = 0;
if (numbers != null) // Important to check for null if no arguments are passed
{
foreach (int number in numbers)
{
sum += number;
}
}
return sum;
}
public static void Main(string[] args)
{
Console.WriteLine("Sum of 1, 2, 3: " + CalculateSum(1, 2, 3)); // Passing individual arguments
Console.WriteLine("Sum of 4, 5, 6, 7: " + CalculateSum(4, 5, 6, 7)); // Passing more arguments
int[] nums = { 8, 9, 10 };
Console.WriteLine("Sum of array {8, 9, 10}: " + CalculateSum(nums)); // Passing an array
Console.WriteLine("Sum of no numbers: " + CalculateSum()); // Passing no arguments
}
}
Concepts Behind the Snippet
The params
keyword provides syntactic sugar, allowing you to call a method with a variable number of arguments without explicitly creating an array each time. The compiler automatically creates the array for you when you pass a comma-separated list of arguments. Only one params
parameter is allowed in a method signature, and it must be the last parameter.
Real-Life Use Case
Consider a logging method that needs to accept a variable number of parameters to format a log message. The params
keyword is very useful here, instead of creating overload methods for each number of parameters you could use the params string[] messageParts
to concatenate all parts of a message.
public static void LogMessage(string severity, string format, params object[] args)
{
string message = string.Format(format, args);
Console.WriteLine($"[{severity}] {message}");
}
Best Practices
null
on the params
array within the method, especially if it's possible for the method to be called without arguments.params
judiciously. Overuse can lead to ambiguity and make the code harder to understand.
Interview Tip
Be prepared to explain the difference between passing a params
argument and passing a regular array. The key difference is how the method is *called*. With params
, the caller can pass a comma-separated list; with a regular array parameter, the caller *must* construct an array before calling the method.
When to use them
Use the params
keyword when:
Memory footprint
The params
keyword allocates memory for the array internally each time the method is called with a comma-separated list. This has a small performance overhead compared to passing an existing array. If performance is critical and the number of arguments is fixed, consider method overloads instead.
Alternatives
Alternatives to using params
includes:
Pros
Cons
null
on the params
array if zero argument passed.params
parameter is allowed in a method signature, and it must be the last one.
FAQ
-
What happens if I pass no arguments to a method that uses the
params
keyword?
Theparams
array will benull
. It's crucial to check fornull
within the method before attempting to iterate over the array or access its elements. Not checking for null will result in aNullReferenceException
. -
Can I have multiple parameters in a method that uses the
params
keyword?
Yes, but only one parameter can be marked with theparams
keyword, and it must be the last parameter in the method signature. All other parameters must be defined before theparams
parameter. -
Can I pass different types of arguments to a
params
parameter?
No. All arguments passed to aparams
parameter must be of the same type, as defined by the array type in the method signature. If you need to pass different types, consider using a common base type (likeobject
) and casting within the method, or use a different approach like method overloading.