Tuesday, September 23, 2008

How to make a function accepting variable arguments of same type in C#

Here is a simple way by which we can declare a function in C# which accepts variable arguments of a particular type.

We have a keyword params in C# which we can use in the parameters in a function.

public class Util
    {
        public static List<int> AddIntegersToList(params int[] integerList)
        {
            List<int> numbers = new List<int>();
            foreach (int item in integerList)
            {
                numbers.Add(item);
            } return numbers;
        }
    }

Now this will accept an array of integers and thus the no of integers which can be passed here is not fixed and hence it fullfills our requirement of a function which can receive variable no of arguments of a single type.

Now for the above function we can use

List<int> listOfIntegers = Util.AddIntegersToList(2, 8, 9, 56, 77);

We can pass here any no of integers.

0 comments :

Post a Comment