- Home /
c# arraylist
class msgclass { public string subject; public string body; }
ArrayList MessageStorage = new ArrayList();
msgclass msg = new msgclass();
msg.subject = "subject";
msg.body = "body";
MessageStorage.Add(msg);
// how to access the msg? // MessageStorage[0][0] doesn't work // MessageStorage[0].subject doesn't work
Answer by Bunny83 · Oct 14, 2011 at 10:50 PM
Well, MessageStorage[0]
does work, but the ArrayList stores only Object references. The compiler can't determine what type you will store there at runtime so you would need to cast it to the right type.
Debug.Log(((msgclass)MessageStorage[0]).subject);
// or
msgclass tmp = (msgclass)MessageStorage[0];
Debug.Log(tmp.subject);
But you should avoid the ArrayList because the casting is quite slow. Use a generic List instead:
//Add this namespace
using System.Collections.Generic;
List<msgclass> MessageStorage = new List<msgclass>();
msgclass msg = new msgclass();
msg.subject = "subject";
msg.body = "body";
MessageStorage.Add(msg);
Debug.Log(MessageStorage[0].subject);
ps. class names should ALWAYS start with a capital letter and usually you use upper camel case so your class name should look like MsgClass
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# ArrayList access from other script 1 Answer