0
0
C Sharp (C#)programming~5 mins

Params keyword for variable arguments in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The params keyword lets you send any number of values to a method without making many overloads. It makes your code simpler and easier to use.

When you want a method to accept a flexible number of inputs, like adding many numbers.
When you want to pass a list of items without creating an array first.
When you want to write a method that can handle zero or more arguments easily.
When you want to collect multiple values into one parameter for processing.
Syntax
C Sharp (C#)
void MethodName(params Type[] parameterName) {
    // method body
}

The params parameter must be the last in the method's parameter list.

You can pass zero or more arguments, and they will be treated as an array inside the method.

Examples
This method prints any number of integers passed to it.
C Sharp (C#)
void PrintNumbers(params int[] numbers) {
    foreach (int num in numbers) {
        Console.WriteLine(num);
    }
}
Calling the method with four numbers directly.
C Sharp (C#)
PrintNumbers(1, 2, 3, 4);
Calling the method with no arguments is allowed.
C Sharp (C#)
PrintNumbers();
You can also pass an array directly.
C Sharp (C#)
int[] arr = {5, 6, 7};
PrintNumbers(arr);
Sample Program

This program shows how to use params to print any number of messages. It works with many or no messages.

C Sharp (C#)
using System;

class Program {
    static void PrintMessages(params string[] messages) {
        Console.WriteLine("You sent " + messages.Length + " messages:");
        foreach (string msg in messages) {
            Console.WriteLine("- " + msg);
        }
    }

    static void Main() {
        PrintMessages("Hello", "How are you?", "Goodbye!");
        PrintMessages();
    }
}
OutputSuccess
Important Notes

You can only have one params parameter in a method.

The params keyword helps avoid creating many method versions for different argument counts.

Summary

Params lets methods accept flexible numbers of arguments.

It must be the last parameter and is treated as an array inside the method.

It makes calling methods easier and your code cleaner.