Anzurio
Anzurio

Reputation: 17014

How to trim an array in .NET?

Say I have an array

array<double>^ buffer = gcnew array<double>(100);

And I want a function that does something like:

void foo(array<double>^% buffer)
{
    Array::Resize(buffer, 10);
}

but that don't allocate and/or move &buffer[0] when you want to trim the array.

Upvotes: 2

Views: 5091

Answers (3)

Alex from Jitbit
Alex from Jitbit

Reputation: 60626

The recent C#/.NET Core versions come with a new type - Span<T> - which is essentially a "view" into an existing array.

Spans can be treated almost like arrays, you can iterate it via foreach etc.

They were invented just for this very purpose - to slice/trim/manipulate arrays without allocating new arrays. BUT you will have to rewrite your API to work with Span datatype (or, after all the array slicing/reslicing is complete, just call ToArray() at the end which will still allocate a new array, but only once all the work is finished)

https://learn.microsoft.com/en-us/dotnet/api/system.span-1?view=net-6.0

Upvotes: 0

thecoop
thecoop

Reputation: 46098

You cannot do this in .NET. Arrays in .NET are of fixed size once allocated; the only way you can change the size of an array is to re-allocate it (which is what Array.Resize does), and this will invariably change the location of the array in memory.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062745

.NET arrays are immutable in size once created. You can't trim it; you must reallocate and copy. So Array.Resize already does everything you need. Perhaps just ignore the elements at the end if you really don't want to do this.

Or; use a List<T>, which encapsulates an array, and does have TrimExcess(). In C# terms:

    var list = new List<int>(100);
    // prints 0/100
    Console.WriteLine("{0} / {1}", list.Count, list.Capacity);
    list.Add(1);
    list.Add(2);
    list.Add(3);
    // prints 3/100
    Console.WriteLine("{0} / {1}", list.Count, list.Capacity);
    list.TrimExcess();
    // prints 3/3
    Console.WriteLine("{0} / {1}", list.Count, list.Capacity);

Upvotes: 5

Related Questions