C# FAQ: Does CSharp support variable method arguments (vararg)

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

Does C# support variable method arguments (vararg)?

Yes. The params keyword can be applied to a method parameter which is an array. Upon method invocation, the array elements can be supplied as a comma (,) separated list.

For example, if the method parameter were an array of object, the source code would be similar to the following:

void paramsExample 
   (object argument-1, 
    object argument-n, 
    params object[] variableArguments) 
{ 
   foreach (object arg in variableArguments) 
   {
   } 
}

And, this method can be invoked with any number of arguments of any type. Here is a sample invocation:

paramsExample (1, 2.3m, 4.5f, "arbitrary string", new UserDefinedType());

But, many developers would prefer to pass a variable number of arguments of a single, specific type—e.g. string—rather than object.


See also


Personal tools