简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM