Variadic Functions in C#

Here’s the translation of the provided code example into C# along with an explanation:

Variadic functions can be implemented in C# using the params keyword, allowing the function to accept a variable number of arguments.

using System;

class Program
{
    // Here’s a function that will take an arbitrary number of ints as arguments.
    static void Sum(params int[] nums)
    {
        Console.Write("[");
        for (int i = 0; i < nums.Length; i++)
        {
            Console.Write(nums[i]);
            if (i < nums.Length - 1)
                Console.Write(", ");
        }
        Console.Write("] ");

        int total = 0;
        foreach (int num in nums)
        {
            total += num;
        }
        Console.WriteLine(total);
    }

    static void Main()
    {
        // Variadic functions can be called in the usual way with individual arguments.
        Sum(1, 2);
        Sum(1, 2, 3);

        // If you already have multiple args in an array, apply them to a variadic function using `params` like this.
        int[] nums = { 1, 2, 3, 4 };
        Sum(nums);
    }
}

The code above defines a Sum method that uses the params keyword to accept a variable number of int arguments, which are treated within the method as an array. The Main method demonstrates calling the Sum method with individual arguments as well as with an array of integers.

To run the program, save it to a file named Program.cs and use the C# compiler and runtime to execute it.

$ csc Program.cs
$ Program.exe
[1, 2] 3
[1, 2, 3] 6
[1, 2, 3, 4] 10

In the steps above, csc compiles the C# code into an executable, and Program.exe runs that executable, outputting the results of the variadic function calls.

Another key aspect of functions in C# is their ability to form closures, which we’ll look at next.