Search code examples
c#parametersparams-keyword

C#: assign array with params argument


What speaks against doing this?:

public struct T
{
    private float[] Elements { get; set; }

    public T(params float[] elements)
    {
        Elements = elements;
    }
}

Could this possibly lead to undefined behaviour? Or will the garbage collector keep the array alive since it is beeing used?


Solution

  • Just to provide an answer and add some details.

    This is perfectly legal. The compiler will in effect transform

    new T(1, 2, 3)
    

    To

    new T(new float[]{1, 2, 3})
    

    Since arrays are reference types the constructor will just assign a reference. And since references are tracked by the garbage collector there is no risk for a memory leak or other issues that may affect c++.

    From the language specification (Emphasis mine)

    Within a method that uses a parameter array, the parameter array behaves exactly like a regular parameter of an array type. However, in an invocation of a method with a parameter array, it is possible to pass either a single argument of the parameter array type or any number of arguments of the element type of the parameter array. In the latter case, an array instance is automatically created and initialized with the given arguments.