Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I expand an array in C# without using the new keyword

Tags:

arrays

c#

char

I have a char array in C#.

var arr = new char[3] { 'a','b','c' };

How do I add spaces to the end of it without creating a new array?

result: arr = { 'a', 'b', 'c', ' ', ' ', ' ' };

This might sound similar to VB.NET's ReDim. But I'm not sure that is what I want either. I want to preserve the elements inside of it and not instantiate a new array behind the scenes.

Is this only possible with Generic Collections and ArrayList?

Thanks

like image 988
The Internet Avatar asked Dec 04 '22 14:12

The Internet


1 Answers

No, this is not possible using an array, generic or otherwise.. AFAIK, there is no way to dynamically resize an array. Use a List instead.

As Martin pointed out in the comments, even the List class uses an array in its internal implementation. If you want to truly be able to dynamically resize a data structure without reinitializing it, you must implement your own version of a linked list.

System.Collections.Generic contains a class called LinkedList that represents a doubly-linked list (meaning that each node has a reference to both the next and the previous node), but I'm not sure if its internal implementation uses an array..

like image 87
Daniel Avatar answered Dec 08 '22 01:12

Daniel