Windows Phone Developers

Friday, September 16, 2011

How to Pass Multiple/Variable Parameters to a Function/Method in C#/.NET

C#/VB.NET Function with dynamic parameters / How to make a function accept infinite number of arguments

Normally a method has a definite number of parameters and they are passed from the calling method. What if you are not sure of the number of parameters or want to be flexible in that. A Simple example can be a Adding machine - which adds any numbers sent .

It is possible to achieve that with params keyword -

private void AddAsManyNumbersAsUCan(params int[] numbers)

{

int iTotal = 0;

foreach (int i1 in numbers)

{

iTotal += i1;

}

Console.WriteLine("Sum of {0} numbers added to {1}",numbers.Length ,iTotal);

}

The above method accepts any number of arguments (provided they are of the same type). The method can be called like:

AddAsManyNumbersAsUCan();

AddAsManyNumbersAsUCan(1,2,3);

AddAsManyNumbersAsUCan(100,-1,23,2121,4562);
Will give the following output




You can change the type of the parameter to a generic one - List etc to have a broader use 
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

1 comment:

  1. hey man thanks,

    your blog is really useful.

    ReplyDelete