array = new ArrayList() but in C#

Ok, its me again. I don't use arrays to often, so I've got another question about them. I'm still converting M2H's chat from UnityScript to C#, but I've run into this issue where he clears the array's data with this line:

//UnityScript
chatEntries = new ArrayList();

I've tried:

chatEntries = new ChatEntries[] chatEntries;

But that will not work. I'm sure its amazingly simple, but what am I doing wrong?

Edit: ArrayList() does indeed exist in C#, I apologize for that statement. ;) I'm currently looking into lists in order to clean the array of the previous values? I'm not sure. I don't know too much about arrays or lists >_<.

Edit again: My initial array problem was solved, but when I change the chatEntries to a List, it causes the 'entry' variable to be unassigned.

4 Answers

4

@Your second edit:

If you create a List it will be empty at the beginning. You have to add elements to the list. ChatEntries is also a class so every instance have to be created:

List<ChatEntries> chatEntries = new List<ChatEntries>();

void AddChatEntry(string aName, string aText)
{
    ChatEntries tmp = new ChatEntries();
    tmp.name = aName;
    tmp.text = aText;
    chatEntries.Add(tmp);
}

I would strongly recommend to rename your class to "`ChatEntry`". An instance of this class represents one single chat entry and not multiple. The variable name chatEntries is correct because it's a list and contains multiple entries.

If you add a proper constructor to your class you can do it alot simpler:

class ChatEntry
{
    public string name = "";
    public string text = "";
    public ChatEntry(string aName, string aText)
    {
        name = aName;
        text = aText;
    }
}

List<ChatEntry> chatEntries = new List<ChatEntry>();

chatEntries.Add(new ChatEntry("Name","The text"));

I also have to add "using Systems.Collections.Generic" to my namespace. Just for anyone else having trouble. :D

–

"using System.Collections.Generic" for people how still have problems

–

Don't use ArrayLists; they've been replaced in most cases by the superior List. That said, ArrayLists most certainly exist in C#. The only reason your JS code wouldn't work in C# is that you didn't put

using System.Collections;

at the top of the script. See? That's the namespace it's in.

The case was that in the confusion of unity script to c#, I mistakenly thought that var chatEntries = ArrayList(); would be ChatEntry[] chatEntries;. That is what messed me up. :P

–

Try this:

List<ChatEntries> chatEntries = new List<ChatEntries>();

If you still want to use ArrayList you can do this:

ArrayList chatEntries = new ArrayList();

ArrayList does exist in C# (it's in the System.Collections namespace), but generally you'll want to use System.Collections.Generic.List instead.

What is the type of 'chatEntries'? (I don't see the declaration in the code that you posted.)

chatEntries is an array. I'm just trying to reset all the values to null.

–