params
params
allows a method parameter to receive a variable number of arguments, i.e. zero, one or multiple arguments are allowed for that parameter.
static int AddAll(params int[] numbers) { int total = 0; foreach (int number in numbers) { total += number; } return total; }
This method can now be called with a typical list of int
arguments, or an array of ints.
AddAll(5, 10, 15, 20); // 50 AddAll(new int[] { 5, 10, 15, 20 }); // 50
params
must appear at most once and if used, it must be last in the argument list, even if the succeeding type is different to that of the array.
Be careful when overloading functions when using the params
keyword. C# prefers matching more specific overloads before resorting to trying to use overloads with params
. For example if you have two methods:
static double Add(params double[] numbers) { Console.WriteLine("Add with array of doubles"); double total = 0.0; foreach (double number in numbers) { total += number; } return total; } static int Add(int a, int b) { Console.WriteLine("Add with 2 ints"); return a + b; }
Then the specific 2 argument overload will take precedence before trying the params
overload.
Add(2, 3); //prints "Add with 2 ints" Add(2, 3.0); //prints "Add with array of doubles" (doubles are not ints) Add(2, 3, 4); //prints "Add with array of doubles" (no 3 argument overload)
params
Table Of Contents
2
Literals
18
Regex
19
DateTime
20
Arrays
22
Enum
23
Tuples
25
GUID
26
BigInteger
28
Looping
29
Iterators
30
IEnumerable
35
Dynamic type
37
Casting
41
Interfaces
47
Methods
52
Keywords
53
Recursion
57
Inheritance
58
Generics
62
Reflection
65
LINQ Queries
66
LINQ to XML
68
XmlDocument
69
XDocument
79
Diagnostics
80
Overflow
86
Properties
89
Events
93
Structs
94
Attributes
95
Delegates
97
Networking
102
Action Filters
103
Polymorphism
104
Immutability
105
Indexer
107
Stream
108
Timers
109
Stopwatches
110
Threading
112
Async Await
114
BackgroundWorker
117
Lock Statement
118
Yield Keyword
121
Func delegates
124
ICloneable
125
IComparable
127
Using SQLite
128
Caching
129
Code Contracts
136
Pointers
144
Hash Functions
146
Cryptography
148
C# Script
149
Runtime Compile
150
Interoperability
156
Contributors