Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving a parameter in an object within an ArrayList in C#?

Tags:

c#

using UnityEngine;
using System.Collections;

public class People{

    public string name;
    public int type;

}

public class Game{
    public ArrayList people;

    public void start(){
        People p = new People();
        p.name = "Vitor";
        p.type = 1;

        people = new ArrayList ();
        people.add(p);

        Debug.Log(p[0].name);
    }
}

Returned error:

Type 'object' does not contain a definition for 'name' and no extension method 'name' of type 'object' could be found (are you missing a using directive or an assembly reference?)

like image 525
SrEdredom Avatar asked Dec 14 '22 08:12

SrEdredom


2 Answers

The ArrayList is comprised of objects, so you need to cast it:

Debug.Log(((People)people[0]).name);
like image 126
NikolaiDante Avatar answered Feb 01 '23 23:02

NikolaiDante


It should be Debug.Log((people[0] as People).name);.

like image 30
romanoza Avatar answered Feb 01 '23 22:02

romanoza