x


How do you initialize a List or Array?

I'd like to know how to initialize a generic list.

I have mylist=new List.<String>();

I can't put mylist[14]="hello"; //because it doesn't exist yet.  
mylist.Insert(14,"hello"); //same problem?  

Do I have to initialize the list somehow?
I tried using things I've seen in a search like ([1..40]) but unity doesn't recognize them.

I can't figure out how to initialize the list with placeholders.

more ▼

asked Mar 06 '12 at 01:43 AM

dansav gravatar image

dansav
373 104 131 154

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

Looks like your list is created, but empty.

myList.Add("hello");

http://msdn.microsoft.com/en-us/library/3wcytfd1.aspx

more ▼

answered Mar 06 '12 at 03:03 AM

rutter gravatar image

rutter
5.1k 2 11

(comments are locked)
10|3000 characters needed characters left

You did initialize it; that's what "mylist=new List.<String>();" does. To add content, use the Add function. http://msdn.microsoft.com/en-us/library/s6hkc2c4(v=vs.80).aspx

more ▼

answered Mar 06 '12 at 02:31 AM

Eric5h5 gravatar image

Eric5h5
80.1k 41 132 519

Maybe initialize is the wrong term. I'm trying to add a value at a specific position. I don't have values for positions 0,1,2,3 only 14. The other values will come in later.

Mar 06 '12 at 02:40 AM dansav

The positions in a List don't exist until you add something. Sounds like you want to use myArray = new String[15]; instead.

Mar 06 '12 at 02:45 AM Eric5h5

I get an error when trying that: Cannot convert 'UnityEngine.String[]' to 'System.Collections.Generic.List.<UnityEngine.String>'

I was hoping to be able to add values at certain positions and that other positions would be null and that I could check to see if a position has a value or is null.

Mar 06 '12 at 06:06 PM dansav

string[] myArray = new string[15];

Mar 06 '12 at 06:10 PM SirGive

The List"" is a first-in-first-out array. Using the Generics will cause it to start from zero and go from there. You would have to insert 14 other empty items into the list before getting to the 15th, where you could provide the value you are looking for.

If you are looking for creating a known size array and you plan on using the last one as you need to, I think you'd be better off creating a standard array String[15] as Eric5h5 said.

var mylist = new String[15]; myList[15] = "hello";

All of the other items will remain empty strings until you change them.

Mar 06 '12 at 06:12 PM Jacob Aldridge
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1355
x354
x37
x28

asked: Mar 06 '12 at 01:43 AM

Seen: 1564 times

Last Updated: Mar 06 '12 at 06:56 PM