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:
xxxxxxxxxx
1
void DoSomething(params String[] argumnets) // <--- multiple arguments by using: params String[]
2
{
3
// some logic here ...
4
5
// int count = arguments.Length;
6
//
7
// argumnets[0]
8
// argumnets[1]
9
// argumnets[2]
10
// ...
11
}
12
13
14
// Using:
15
16
DoSomething();
17
DoSomething("arg 1");
18
DoSomething("arg 1", "arg 2");
19
DoSomething("arg 1", "arg 2", "arg N");
Simple case:
Definition syntax |
xxxxxxxxxx 1 ResultType MethodName(params ArgumentsType[] arguments) 2 { 3 /* ... */ 4 } |
Calling syntax |
xxxxxxxxxx 1 ResultType result = MethodName( 2 paramVariable1, 3 paramVariable2, 4 // ... 5 paramVariableN 6 ); |
Description |
By adding Using that construction it is required to:
The number of total arguments depends on function calling. |
Composed cases:
Definition syntax |
xxxxxxxxxx 1 ResultType MethodName( 2 ArgumentType1 argument1, 3 ArgumentType2 argument2, 4 // ... 5 ArgumentTypeN argumentN, 6 params ArgumentsType[] arguments 7 ) { 8 /* ... */ 9 } |
Calling syntax |
xxxxxxxxxx 1 ResultType result = MethodName( 2 variable1, variable2, variableN, /* ... */ 3 paramVariable1, paramVariable2, paramVariableN /* ... */ 4 ); |
In ths section you can see 2 example cases:
- multiple arguments function,
- normal arguments function extended with additional arguments.
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main(String[] args)
6
{
7
DoSomething();
8
DoSomething("arg 1", "arg 2");
9
DoSomething("arg 1", "arg 2", "arg 3", "arg N");
10
11
DoSomething(1, 2, 3);
12
DoSomething(1, 2, 3, "arg 1", "arg 2");
13
DoSomething(1, 2, 3, "arg 1", "arg 2", "arg 3", "arg N");
14
}
15
16
private static void DoSomething(params String[] arguments)
17
{
18
Console.WriteLine("Arguments count: " + arguments.Length);
19
}
20
21
private static void DoSomething(int a, int b, int c, params String[] arguments)
22
{
23
Console.Write("a=" + a + ", ");
24
Console.Write("b=" + b + ", ");
25
Console.Write("c=" + c + ", ");
26
Console.WriteLine("Arguments count: " + arguments.Length);
27
}
28
}
Output:
xxxxxxxxxx
1
Arguments count: 0
2
Arguments count: 2
3
Arguments count: 4
4
a=1, b=2, c=3, Arguments count: 0
5
a=1, b=2, c=3, Arguments count: 2
6
a=1, b=2, c=3, Arguments count: 4