The 'params' Keyword
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 47 of 70.
The params keyword lets a method accept a variable number of arguments of the same type. Instead of requiring callers to create an array manually, they can pass arguments directly, separated by commas.
Place params before an array parameter in the method signature:
public static int Sum(params int[] numbers)
{
int total = 0;
foreach (int n in numbers)
total += n;
return total;
}
// All of these calls work
Console.WriteLine(Sum(1, 2)); // 3
Console.WriteLine(Sum(1, 2, 3, 4, 5)); // 15
Console.WriteLine(Sum()); // 0 (empty array)The compiler automatically wraps the arguments into an array. You can also pass an existing array directly if you already have one:
int[] values = { 10, 20, 30 };
Console.WriteLine(Sum(values)); // 60There are a few rules to remember: a method can have only one params parameter, and it must be the last parameter in the list. You can combine it with regular parameters:
public static void Log(string prefix, params object[] items)
{
foreach (var item in items)
Console.WriteLine(prefix + item);
}
Log("Item: ", "Apple", 42, true);The params keyword makes APIs more flexible and caller-friendly, which is why you see it in methods like Console.WriteLine and string.Format.
Challenge
EasyLet's build a flexible message formatter that uses the params keyword to handle any number of values. You'll create a utility class that can format messages with variable arguments, demonstrating how params makes methods more versatile and caller-friendly.
You'll organize your code across two files:
MessageFormatter.cs: Create aMessageFormatterclass in theFormattingnamespace with two methods that useparams:Combine(params string[] parts)- joins all provided strings with a space between them and returns the resultFormatList(string label, params int[] numbers)- combines a regular parameter with aparamsarray. It should return the label followed by a colon, then all numbers separated by commas (e.g.,Scores: 85, 90, 78)
Program.cs: In your main file, demonstrate both methods with inputs. Read a label string, then read a line of comma-separated integers. UseCombineto join three fixed words, and useFormatListto display the label with the numbers.
You will receive two inputs:
- A label string (e.g.,
Scores) - A comma-separated list of integers (e.g.,
85,90,78,92)
First, call Combine with the words "Hello", "params", and "world!" and print the result. Then parse the comma-separated integers into an array and call FormatList with the label and the integer array, printing that result as well.
For example, if the inputs are Scores and 85,90,78, the output should be:
Hello params world!
Scores: 85, 90, 78Notice how Combine accepts any number of strings directly, while FormatList shows that you can mix regular parameters with params - the params parameter just needs to come last. You can also pass an existing array to a params method, which is exactly what you'll do with the parsed integers!
Cheat sheet
The params keyword allows a method to accept a variable number of arguments of the same type without requiring callers to create an array manually:
public static int Sum(params int[] numbers)
{
int total = 0;
foreach (int n in numbers)
total += n;
return total;
}
// All of these calls work
Console.WriteLine(Sum(1, 2)); // 3
Console.WriteLine(Sum(1, 2, 3, 4, 5)); // 15
Console.WriteLine(Sum()); // 0 (empty array)You can pass an existing array directly to a params method:
int[] values = { 10, 20, 30 };
Console.WriteLine(Sum(values)); // 60Rules for params:
- A method can have only one
paramsparameter - It must be the last parameter in the list
- Can be combined with regular parameters
public static void Log(string prefix, params object[] items)
{
foreach (var item in items)
Console.WriteLine(prefix + item);
}
Log("Item: ", "Apple", 42, true);Try it yourself
using System;
using Formatting;
class Program
{
public static void Main(string[] args)
{
// Read inputs
string label = Console.ReadLine();
string numbersInput = Console.ReadLine();
// TODO: Use MessageFormatter.Combine with "Hello", "params", and "world!"
// and print the result
// TODO: Parse the comma-separated integers into an int array
// Hint: Split the string and convert each part to int
// TODO: Use MessageFormatter.FormatList with the label and the int array
// and print the result
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator