Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objects in a c# arraylist

I'm coming from a Javascript background which possibly is a good thing although so far it's proving to be a bad thing.

In Javascript, I have:

function doStuff(){
    var temp = new Array();
    temp.push(new marker("bday party"));
    alert(temp[0].whatsHappening); // 'bday party' would be alerted
}

function marker(whatsHappening) {
    this.whatsHappening = whatsHappening;
}

I would now like to do the same thing in C#. I have set up a class:

class marker
{
    public string whatsHappening;

    public marker(string w) {
        whatsHappening = w;
    }
} 

and add a new object, but I can't seem to call the data in the same way:

ArrayList markers = new ArrayList();

markers.Add(new marker("asd"));
string temp = markers[0].whatsHappening; // This last bit isn't allowed
like image 780
Chris Avatar asked Dec 13 '22 08:12

Chris


2 Answers

Use a generic List<T> instead:

List<marker> markers = new List<marker>();
markers.Add(new marker("asd"));
string temp = markers[0].whatsHappening;
like image 117
Darin Dimitrov Avatar answered Dec 14 '22 23:12

Darin Dimitrov


ArrayList is weakly typed. That means, all items in the array are objects. You need to cast them to your class:

string temp = ((marker)markers[0]).whatsHappening;

You should use a List<marker> instead.

like image 43
Candide Avatar answered Dec 14 '22 22:12

Candide