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.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s


A great site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: