A method that accepts a variable number of parameters in C#

This may be old news to you, but I have learned the existence of something like that in C# just now.

C# offers a very elegant solution to this problem with something called parameter arrays.

The signature of the method should be something like this:

void PassDynamicNumberofParameters (params int[] parameters)

Note the params keyword here.

The catch is that, a parameter array has to come at the end of the list of parameters, and must be a single-dimensional array.

You can then either create an array yourself such as

int[] x = {1, 2, 3};

and then pass it into your function, (which you could do in any language by creating a method that accepts an array containing the parameters, an object array probably)

PassDynamicNumberofParameters(x);

or, you can just give any number of parameters as you want! 🙂

PassDynamicNumberofParameters(3,6,9,12,233,111);

Pretty cool isn't it? ;)
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: