Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# version of Array.Unshift() from UnityScript?

I'm trying to write a simple chat box, and I found a really simple piece of code for it on the unity forums, but its in UnityScript (similar to JavaScript).

I tried to convert the code to C# and I've had some success, but the problem is that the code uses Array.Unshift(), which prepends an item to an array. I'm trying to find some simple way of doing this in C#, but for the life of me I can't get it to work.

What is the C# equivalent of Array.Unshift?

like image 787
Matrixian Avatar asked Feb 22 '14 08:02

Matrixian


2 Answers

As per my understanding .Unshift method adds items to the start of array and return new length of array.

You can use List<T> collection in C#. To add items at first position of (prepond) to list use following way.

List<T>.Insert(0, item); // this will insert item at first position

Also you can convert this list to array using .ToArray() method of list.

like image 54
Priyang Avatar answered Oct 24 '22 01:10

Priyang


It's tricky with C# arrays. You need to make a new array and copy all elements from the old one, plus the extra element to insert. I suggest using List<T> instead, or maybe rethink the algorithm so it doesn't need it.

like image 28
Vilx- Avatar answered Oct 24 '22 01:10

Vilx-