C# Functions Part 3


The params keyword used in a C# function.

class Program  // Functions - params keyword
{
    static int SumIntVals(ref string myStr, params int[] vals)
    {  // params must be last in the list
        myStr = "Hello " + myStr;
        int sum = 0;
        foreach (int val in vals)
        {  // they must all be int type
            sum += val;
        }
        // can pass in no integers if you want
        return sum;
    }
    static void Main(string[] args)
    {
        int myInt = 2;
        string strMe = "Mike";
        int sum = SumIntVals(ref strMe, 1, myInt, 5, 3);
        // must use ref otherwise Hello will not
        // be concatenated to the strMe variable!
        WriteLine($"{strMe}, your summed values = {sum}");
        ReadKey();
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *