Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

parameters - 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?

question from:https://stackoverflow.com/questions/66048594/c-assign-array-with-params-argument

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...