2

I am new to C#, and am wondering how to do the following:

I create an array whose size of the maximum number of elements I will need to store:

int[] myArray = new int[64000];

I am passing this array to a 3rd party API. In this API, they use the .Length property to determine the number of elements. I don't want this to happen because the array length is the maximum count, not the "active count" (i.e. the number of elements in use).

With this in mind, is there a way to create another array, whose size equals the active count? And, can this be done without a copy and/or allocation? I already have the allocated memory -- all I want to do is indicate the subregion of interest while playing nicely with the 3rd party API.

4
  • 1
    Sounds like you should be using a List rather than an array, if you do not know exactly how many items will be in the collection.
    – Servy
    Apr 21, 2014 at 19:11
  • 1
    What is the exact declaration of the API part (method?) that accepts your array? Apr 21, 2014 at 19:20
  • I'm using Unity, and the what I'm doing is populating/managing vert/normal/tangent/uv/triangle arrays. I want to have a pool of these arrays, where each array is a predetermined maximum size. Then, as content comes/goes, the arrays become populated (not always to 100%), and I pass them off to an instance of UnityEngine.Mesh (link). Apr 21, 2014 at 20:23
  • To populate the arrays in UnityEngine.Mesh, I just assign an array reference. There is no copy. If I want to manage my own pools, I now have to allocate arrays that are the exact sizes, and let them get garbage collected. This defeats the point of using these pools. I would rather manage my own memory, but I'm not seeing many options here ... Apr 21, 2014 at 20:25

1 Answer 1

5

If the third party API accepts an int[], the only way to pass your data in would be to copy.

An API could easily be designed where this isn't necessary (ie: pass the number of elements, or use ArraySegment<T>, etc), but if the API doesn't support it, a copy will be required.

Note that you can use Array.Copy to bulk-copy the items, however, instead of doing copying in a loop.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.