Learn how an ArrayList can be shared between different classes in a C# program. In other words, how to pass Arraylist from one class to another in C#.
We’ll create an ArrayList in the main() method and will share it to the two different classes i.e. the Read and the Write class.
The Write class will add elements to an ArrayList and another Read class will read elements from the same ArrayList.
Logic is simple.
Create a list using an jSystem.Collections.Generic in the main() of the Sample class. Pass the same ArrayList to constructor of both Read and Write class constructor and initialize the list fields of both class. Perform operations add or remove on that list.
Code Example to Share ArrayList between classes.
using System;
using System.Collections.Generic;
/*
* This class will add elements to
* a shared list that is created with an Arraylist.
*/
class Write
{
private List<String> list;
// Receive a shared list in constructor
public Write(List<String> list)
{
this.list = list;
}
// add items
public void addItem(String item)
{
this.list.Add(item);
}
}
class Read
{
private List<String> list;
// Receive shared list in constructor
public Read(List<String> list)
{
this.list = list;
}
// Read the items
public void readItem() {
foreach (String item in list){
Console.WriteLine(item);
}
}
}
class Sample
{
static void Main(string[] args)
{
List<string> list = new List<string>();
Write w = new Write(list);
Read r = new Read(list);
w.addItem("Apple");
w.addItem("Mange");
r.readItem();
}
}
Output:
Apple
Mange