C# Params Array
Introduction
When writing C# functions, you might sometimes encounter situations where you don't know exactly how many arguments you need to pass. For instance, imagine creating a function to calculate the sum of numbers - would you create separate functions for two, three, or four parameters? This is where the params
keyword comes to the rescue!
The params
keyword in C# allows a method to accept a variable number of arguments. This feature makes your code more flexible and often eliminates the need for method overloading. In this tutorial, we'll dive into the params array, understand how it works, and see practical examples of its applications.
Understanding the Params Keyword
The params
keyword creates a method parameter that can take a variable number of arguments. The parameter type must be a single-dimensional array.
Basic Syntax
return_type MethodName(params type[] parameterName)
{
// Method code
}
Using Params Arrays
Example 1: Simple Sum Calculator
Let's create a function that calculates the sum of any number of integers:
using System;
class Program
{
static void Main()
{
// Call with different number of arguments
Console.WriteLine($"Sum of 2 numbers: {Sum(5, 10)}");
Console.WriteLine($"Sum of 3 numbers: {Sum(5, 10, 15)}");
Console.WriteLine($"Sum of 5 numbers: {Sum(5, 10, 15, 20, 25)}");
// Call with no arguments
Console.WriteLine($"Sum of no numbers: {Sum()}");
}
static int Sum(params int[] numbers)
{
int total = 0;
foreach (int num in numbers)
{
total += num;
}
return total;
}
}
Output:
Sum of 2 numbers: 15
Sum of 3 numbers: 30
Sum of 5 numbers: 75
Sum of no numbers: 0
In this example, the Sum
method accepts any number of integers. You can call it with different numbers of arguments, and it will work correctly in all cases.
Example 2: Working with Multiple Parameter Types
The params
parameter must be the last parameter in the method definition. You can have other parameters before it:
using System;
class Program
{
static void Main()
{
// Provide a message and numbers
PrintNumbers("Even numbers:", 2, 4, 6, 8);
PrintNumbers("Odd numbers:", 1, 3, 5, 7, 9);
}
static void PrintNumbers(string message, params int[] numbers)
{
Console.WriteLine(message);
foreach (int num in numbers)
{
Console.WriteLine(num);
}
Console.WriteLine();
}
}
Output:
Even numbers:
2
4
6
8
Odd numbers:
1
3
5
7
9
The method PrintNumbers
takes a string message and then any number of integers.
Passing Arrays to Params Parameters
You can also pass an array directly to a method with a params parameter:
using System;
class Program
{
static void Main()
{
int[] myNumbers = { 1, 2, 3, 4, 5 };
// Pass the array directly to the method
int sum = Sum(myNumbers);
Console.WriteLine($"Sum of array elements: {sum}");
}
static int Sum(params int[] numbers)
{
int total = 0;
foreach (int num in numbers)
{
total += num;
}
return total;
}
}
Output:
Sum of array elements: 15
Real-World Application: String Formatting
A classic example of params usage in the .NET Framework is the string.Format
method:
using System;
class Program
{
static void Main()
{
// Using String.Format which uses params internally
string formatted = string.Format("Name: {0}, Age: {1}, Job: {2}", "John", 30, "Developer");
Console.WriteLine(formatted);
// Our own similar implementation
string customFormatted = CustomFormat("Product: {0}, Price: {1}, Stock: {2}",
"Laptop", "$999", 50);
Console.WriteLine(customFormatted);
}
static string CustomFormat(string format, params object[] args)
{
// Simple implementation to replace placeholders
string result = format;
for (int i = 0; i < args.Length; i++)
{
string placeholder = "{" + i + "}";
result = result.Replace(placeholder, args[i].ToString());
}
return result;
}
}
Output:
Name: John, Age: 30, Job: Developer
Product: Laptop, Price: $999, Stock: 50
Real-World Application: Logger Utility
Here's another practical example - a simple logging utility that can accept any number of log parameters:
using System;
class Logger
{
public enum LogLevel
{
Info,
Warning,
Error
}
public void Log(LogLevel level, params object[] messages)
{
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Console.Write($"[{timestamp}] {level}: ");
foreach (var message in messages)
{
Console.Write($"{message} ");
}
Console.WriteLine();
}
}
class Program
{
static void Main()
{
Logger logger = new Logger();
// Log with different number of parameters
logger.Log(Logger.LogLevel.Info, "Application started");
logger.Log(Logger.LogLevel.Warning, "Low memory:", "Only 100MB available");
logger.Log(Logger.LogLevel.Error, "Database connection failed:",
"Timeout exceeded", "Server:", "db.example.com");
}
}
Output:
[2023-09-25 14:30:22] Info: Application started
[2023-09-25 14:30:22] Warning: Low memory: Only 100MB available
[2023-09-25 14:30:22] Error: Database connection failed: Timeout exceeded Server: db.example.com
Best Practices and Considerations
-
Use Sparingly: While params is powerful, don't overuse it. Sometimes having well-defined parameters makes your code more readable and maintainable.
-
Performance Impact: Using params creates a new array every time the method is called, which might impact performance in tight loops or performance-critical code.
-
Always Last Parameter: The params keyword must always be applied to the last parameter of a method.
-
Type Safety: All the arguments passed must be implicitly convertible to the params array type.
Common Mistakes to Avoid
// WRONG - params must be the last parameter
void WrongMethod(params int[] numbers, string message) { }
// RIGHT
void CorrectMethod(string message, params int[] numbers) { }
// WRONG - only one params parameter is allowed
void AnotherWrongMethod(params int[] numbers, params string[] names) { }
// WRONG - params must be a single-dimensional array
void YetAnotherWrongMethod(params int[,] matrix) { }
Summary
The params
keyword in C# is a powerful feature that allows methods to accept a variable number of arguments. It enhances code flexibility, reduces the need for method overloading, and can make your code cleaner and more intuitive.
When used properly, params arrays can significantly improve the usability of your methods, especially for those that naturally work with a variable number of inputs like sum, average, concatenation, or formatting functions.
Remember that while params offers flexibility, it comes with some performance overhead due to array creation. For most applications, this overhead is negligible, but for performance-critical code, you might want to consider alternatives.
Practice Exercises
-
Create a method that finds the maximum value among any number of doubles provided.
-
Implement a
Concatenate
method that joins any number of strings with a given separator. -
Write a
Calculate
method that takes an operation string (like "add", "multiply") and performs that operation on any number of integers provided. -
Build a simple command-line menu system where each menu option can take a variable number of parameters.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)