views:

61

answers:

3

C# spec. allows you to call a function

void foo(params int[] x)

with zero parameters. However, I didn't find in C# Lang. Spec. a word on further behaviour -- will foo get empty array or null reference? I checked also MSDN -- nothing.

Where the behaviour is defined?

NOTE: I am not asking how VS behaves, I am asking about design of the language.

A: 

For the callee it is equal to void foo(int[] x) and passing n parameters will give you an array with n elements. So zero parameters will be translated into an int[0].

deltreme
+8  A: 

17.5.1.4 Parameter arrays

A parameter array permits arguments to be specified in one of two ways in a method invocation:

• The argument given for a parameter array can be a single expression of a type that is implicitly convertible (§13.1) to the parameter array type. In this case, the parameter array acts precisely like a value parameter.

• Alternatively, the invocation can specify zero or more arguments for the parameter array, where each argument is an expression of a type that is implicitly convertible (§13.1) to the element type of the parameter array. In this case, the invocation creates an instance of the parameter array type with a length corresponding to the number of arguments, initializes the elements of the array instance with the given argument values, and uses the newly created array instance as the actual argument.

In the same section an example is given:

using System;
class Test
{
    static void F(params int[] args) {
        Console.Write("Array contains {0} elements:", args.Length);
        foreach (int i in args)
            Console.Write(" {0}", i);
        Console.WriteLine();
    }

    static void Main() {
        int[] arr = {1, 2, 3};
        F(arr);
        F(10, 20, 30, 40);
        F();
    }
}

produces the output

Array contains 3 elements: 1 2 3 Array
contains 4 elements: 10 20 30 40 Array
contains 0 elements:

This example illustrates the expected behavior: empty array

Darin Dimitrov
+8  A: 

Section 7.4.1 of the C# Language Specification

In particular, note that an empty array is created when there are zero arguments given for the parameter array.

It's literally the last line of the section (C# 3.0 spec)

Anthony Pegram
MS well hide this info, I checked the params section ;-) Thank you very much.
macias