- Home /
Adding to an array - C#
Well It's quite simple. I was wondering if you guys knew a way to do this in C#? I've been looking on answers for a while now. But noone really had the same problem as I do.
Answer by whydoidoit · Jul 14, 2012 at 08:55 PM
Add a using System.Collections.Generic and use a generic List instead. Lists have array access syntax, but allow Add, Remove and Insert operations.
List<string> myList = new List<string>();
myList.Add("hello");
Debug.Log(myList[0]);
thanks. But I get a nullrefference exception though ... Can that be because you cant add to an empty List? (I use GameObject arrays)
You can add to an empty list, but only if the list itself exists. $$anonymous$$ight be a good time to post the problematic code.
I officially don't like this comment system. I'm fighting it just trying to type brackets.
You need to instantiate selectedUnits with the "new" command. Right now it's null.
private List<GameObject> selectedUnits = new List<GameObject>();
Yeah it has got worse since UDN. Pretty much have to indent for code and then it doesn't always work
Answer by ivanek333 · May 09, 2019 at 11:47 AM
Is there any function like push_back in C++ for arrays?
Arrays in C# are not really meant to be resized repeatedly, consider using a List
as suggested in the accepted answer.
If it's exceptionally, see the following links
Right, also C++ arrays do not have a push_back method. Only vectors have and the List class in C# is the equivalent of the C++ vector type template. Note that the C++ list type is not an array but a linked list. Besides the container types there's also the native array in C++ which has no methods at all since it's just syntactic sugar for pointer arithmetic.
Your answer
Follow this Question
Related Questions
How to set array length in unity USING C# 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Adding to an Array 1 Answer
Assign a String to Each int 1 Answer