Params Array : params « Language Basics « C# / C Sharp






Params Array

 

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

class Util {
    public static int Sum(params int[] paramList) {
        if (paramList == null) {
            throw new ArgumentException("Util.Sum: null parameter list");
        }

        if (paramList.Length == 0) {
            throw new ArgumentException("Util.Sum: empty parameter list");
        }

        int sumTotal = 0;
        foreach (int i in paramList) {
            sumTotal += i;
        }
        return sumTotal;
    }
}
class Program {
    static void Entrance() {
        Console.WriteLine(Util.Sum(10, 9, 8, 7, 6, 5, 4, 3, 2, 1));
    }

    static void Main() {
        try {
            Entrance();
        } catch (Exception ex) {
            Console.WriteLine("Exception: {0}", ex.Message);
        }
    }
}

 








Related examples in the same category

1.Normal parameter and params parameters
2.Check the array length for params parameters
3.use the params feature to write functions which accept a variable number of arguments
4.Use params to mark parameter