How to

use variable number of arguments for method

Published: 3. November 2011 | Updated: 3. November 2011
License: Microsoft Public License (MS-PL)
Categories: Framework
Tags: C#
Was this snippet helpful for you? YESYES / NONO

Method

public static double Avg(params int[] values)
{
    double sum = 0;
    foreach (int value in values)
    {
        sum += value;
    }
    return sum / values.Length;
}

Use

double avg = Avg(44);
Console.WriteLine(avg);

avg = Avg(5, 32);
Console.WriteLine(avg);

avg = Avg(5, 31, 79, 120, 413, 973, 1010);
Console.WriteLine(avg);
Console Output:
44
18.5
375.857142857143
Send us feedback about this snippet »



Related Snippets: