
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Arithmetic Operators
- C# - Assignment Operators
- C# - Relational Operators
- C# - Logical Operators
- C# - Bitwise Operators
- C# - Miscellaneous Operators
- C# - Operators Precedence
- C# Conditional Statements
- C# - Decision Making
- C# - If
- C# - If Else
- C# - Nested If
- C# - Switch
- C# - Nested Switch
- C# Control Statements
- C# - Loops
- C# - For Loop
- C# - While Loop
- C# - Do While Loop
- C# - Nested Loops
- C# - Break
- C# - Continue
- C# OOP & Data Handling
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
C# - Params Arrays
At the times, when declaring a method, we are not sure of the number of arguments passed as a parameter. In C#, a params array (or parameters array) allows us to pass a variable number of arguments to a method. We use the params keyword in the method's parameter list.
C# params Keyword
C# params keyword allows you to pass multiple values (a variable number of arguments) to a function without making an array. That means you do not need to create an array and pass array name as an argument.
Syntax
Here is the syntax of passing arguments with params keyword:
returnType FunctionName(params dataType[] parameterName) { // Function body }
Example of Params Arrays
Following is the basic example of the params array. Here, the PrintNumbers
method uses the params keyword to indicate that it can take a variable number of int
arguments.
using System; class Program { static void Main() { PrintNumbers(1, 2, 3, 4, 5); PrintNumbers(10, 20, 30); PrintNumbers(); } // Method using params array static void PrintNumbers(params int[] numbers) { foreach (int num in numbers) { Console.WriteLine(num); } } }
Following is the output of the code −
1 2 3 4 5 10 20 30
Using params with Different Data Types
You can also use params keyword with different types of values such as strings, objects, or custom types.
Example
In the following example, we use the params keyword to pass multiple city names to a function, which then prints each city:
using System; class Program { static void PrintCities(params string[] cities) { foreach (string city in cities) { Console.WriteLine(city); } } static void Main() { PrintCities("Delhi", "Mumbai", "Bangalore", "Chennai", "Kolkata"); } }
When executed, this program outputs:
Delhi Mumbai Bangalore Chennai Kolkata