main banner

Development

Methods in .NET - Parameter with variable number of arguments (Part 2)

In the previous article we had an overview of the article and we visited the Named and Optional arguments.


The ref and out keywords are often used to change the behavior of parameters in a method. However, there’s a keyword that is much less known, but which is quite helpful: params. When using params, before any parameter declaration, it will allow us to provide a variable number of arguments when calling the method. The parameter using the params keyword contains the restriction that it has to be declared as an array.

To exemplify the usage of this type of argument, let’s declare a method that will sum all the terms provided in the call to the method.

Methods in .NET

As we can see, we are receiving an integer array of terms, and in the implementation we are iterating through it to get the sum of all the numbers provided. In the following code we are calling the method three times with different arguments.

Methods in .NET

In the first call, we provided one argument; we might as well send zero arguments i.e. an empty array. In the second call we used three arguments separated by commas. In the third call we sent an array of terms. These are the possible ways to call a method with a parameter using the params keyword. The output for these calls is the following:

Methods in .NET

The usage of the params keyword is bounded to the following conditions:

  • Only one parameter can have this keyword
  • This parameter must be the last in the formal parameters list

For part three we will see in detail how to define and use extension methods.


Osvaldo G.

Calling Osvaldo “el Doc” is no coincidence, he is part of the Inflection Point’s gurus and has been working in the company for 9 years; his degree in Computer Engineering, the numerous certifications and more than 15 years of experience in Microsoft technologies, have made of him a mentor for many and also an avid writer for Inflection Point’s blog with tips and facts that have saved more than one coder in their quest for better coding. He comes from San Nicolás de los Garza, Nuevo Leon and is a Tigres (local soccer team) fan.

Articles