.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);