Hydrargyrum
Hydrargyrum

Reputation: 3816

Constructing an array out of existing arrays in C# - will this create copies in memory?

In my C# code, I have constructed four arrays of data:

double[] values;
DateTime[] timestamps;
long[] qualities;
long[] reasons;

These arrays need to be passed to an external API. The API method call is somewhat indirect; its signature looks like invokeApiMethod(string apiMethodName, Object[] apiMethodParams).

In this case, the external API method call expects four arrays of the kind that I have already constructed.

If I construct the Object[] using the following code:

Object[] apiMethodParams = { values, timestamps, qualities, reasons };

Will this result in all four existing arrays being copied into a large contiguous block of new memory? Or will C# just pass an array of references to the existing arrays to the external API?

Upvotes: 2

Views: 639

Answers (3)

iefpw
iefpw

Reputation: 7042

They are references. Copying and creating uses the "new" keyword.

Upvotes: 0

Tilak
Tilak

Reputation: 30698

http://www.mbaldinger.com/post/C-reference-types-are-passed-by-value!.aspx

http://answers.yahoo.com/question/index?qid=20090105141923AAt63hD

In case you need to pass different array, you need to clone/copy it and then pass the cloned/copied array

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500425

Will this result in all four existing arrays being copied into a large contiguous block of new memory? Or will C# just pass an array of references to the existing arrays to the external API?

The latter. It will be an array of four elements, each element of which is a reference. The values of values, timestamps etc are just references to arrays.

Note that you may want to take a copy of some or all of the arrays if the external API modifies the array contents, and you want the original values - but that won't happen automatically.

Upvotes: 4

Related Questions