EN
C# - multiple parameters in method
7
points
In this short article, we would like to show how to pass multiple arguments to function in C#.
Quick solution:
void DoSomething(params String[] argumnets) // <--- multiple arguments by using: params String[]
{
// some logic here ...
// int count = arguments.Length;
//
// argumnets[0]
// argumnets[1]
// argumnets[2]
// ...
}
// Using:
DoSomething();
DoSomething("arg 1");
DoSomething("arg 1", "arg 2");
DoSomething("arg 1", "arg 2", "arg N");
1. Documentation
Simple case:
| Definition syntax |
|
| Calling syntax |
|
| Description |
By adding Using that construction it is required to:
The number of total arguments depends on function calling. |
Composed cases:
| Definition syntax |
|
| Calling syntax |
|
Practical example
In ths section you can see 2 example cases:
- multiple arguments function,
- normal arguments function extended with additional arguments.
using System;
public class Program
{
public static void Main(String[] args)
{
DoSomething();
DoSomething("arg 1", "arg 2");
DoSomething("arg 1", "arg 2", "arg 3", "arg N");
DoSomething(1, 2, 3);
DoSomething(1, 2, 3, "arg 1", "arg 2");
DoSomething(1, 2, 3, "arg 1", "arg 2", "arg 3", "arg N");
}
private static void DoSomething(params String[] arguments)
{
Console.WriteLine("Arguments count: " + arguments.Length);
}
private static void DoSomething(int a, int b, int c, params String[] arguments)
{
Console.Write("a=" + a + ", ");
Console.Write("b=" + b + ", ");
Console.Write("c=" + c + ", ");
Console.WriteLine("Arguments count: " + arguments.Length);
}
}
Output:
Arguments count: 0
Arguments count: 2
Arguments count: 4
a=1, b=2, c=3, Arguments count: 0
a=1, b=2, c=3, Arguments count: 2
a=1, b=2, c=3, Arguments count: 4