How to pass any number of parameters into a method in C# .NET

You must have come across built-in methods in .NET where you can send any number of arguments into a method. E.g. string.Format has an overload where you can pass in a format string and then an array with the “params” modifier.

There’s nothing stopping you from using the same keyword to write a similar method, here’s an example:

public void MethodWithParams(int toBeMultiplied, params int[] multipliers)
	foreach (int m in multipliers)
		Console.WriteLine(string.Format("{0} x {1} = {2}", toBeMultiplied, m, toBeMultiplied * m));

The above method will go through the integer array in the “multipliers” arrays and multiplies each element with “toBeMultiplied”. Here’s an example on how to call the above method:

MethodWithParams(5, 1, 2, 3, 4, 5, 6);

The first parameter will be set to “toBeMultipled”, the others will be passed into the params array. Some rules to remember:

  • The params parameter must come last in the parameters list in the method’s signature
  • It’s optional to pass in any argument to the params array, so MethodWithParams(5); is also a valid call.
  • There cannot be more than one params array in the parameters list
  • There can be any number of other parameters in the method signature as long as the params parameter comes last

View all various C# language feature related posts here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to How to pass any number of parameters into a method in C# .NET

  1. Gabriel RB says:

    Reblogged this on Gabriel and commented:
    Ótima dica.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: