Awais Ahmad Awais Ahmad - 17 days ago 5
C# Question

add an object of a class into arraylist and then retrieve it's data member using arraylist

using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace classQuiz
{
class A {
public int a = 100;
public int b = 200;
}
class Program
{
static void Main(string[] args)
{
A obj = new A();//object of that class
ArrayList list = new ArrayList();
list.Add(obj);//passing object
Console.WriteLine(list[0]);//output down the code
Console.ReadKey();
}
}
}


Output:-

classQuiz.A


In this program i am passing object to array list what i want is how can i write its data members on console using array list.I want to access them using array list.I have tried

list[0].a;
//or
list[0].b;


What can be done to acheive this?

+


i do not want to change arraylist to List
I m really very confused. :D

Answer

Your problem occurs as an ArrayList is just a collection of objet-instances which donĀ“t have any knowledge on your actual types. So you have towo possibilites:

  1. cast every item to its actual type:

    A obj = new A();//object of that class
    ArrayList list = new ArrayList();
    list.Add(obj);//passing object
    ((A)list[0]).a = 1;            // list[0] is just object
    
  2. or the better approach: use a generic collection, such as List<T> which is strongly-typed:

    A obj = new A();//object of that class
    List<A>list = new List<A>();
    list.Add(obj);//passing object // list[0] is of your actual type
    obj.a = 1;
    
Comments