7/26/2010

C# Params Array




params array:
-------------
If a method takes params array as a parameter, that parameter can accept any number of arguments.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication20
{
    class demo
    {
        public void add(params int[] a)
        {
            int sum = 0;

            for (int i = 0; i < a.Length; i++)
            {
                sum = sum + a[i];
            }
            Console.WriteLine("Sum of " + a.Length + " numbers is " + sum);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            demo d = new demo();
            d.add(56, 4);
            d.add(1, 2, 3, 4, 5);
            d.add(6, 9, 3);
        }
    }
}

No comments:

Post a Comment