Access List from another class

72,482

Solution 1

public class MyClass {

    private List<string> myList = new List<string>();

    public List<string> GetList()
    {
        return myList;
    }
} 

You can have any anything there instead of string. Now you can make an object of MyClass and can access the public method where you have implemented to return myList.

public class CallingClass {

    MyClass myClass = new MyClass();

    public void GetList()
    {
        List<string> calledList = myClass.GetList();
        ///More code here...
    }
}

Solution 2

To create a list call the list constructor:

class Foo
{
    private List<Item> myList = new List<Item>();
}

To make it accessible to other classes add a public property which exposes it.

class Foo
{
    private List<Item> myList = new List<Item();

    public List<Item> MyList
    {
        get { return myList; }
    }
}

To access the list from another class you need to have a reference to an object of type Foo. Assuming that you have such a reference and it is called foo then you can write foo.MyList to access the list.

You might want to be careful about exposing Lists directly. If you only need to allow read only access consider exposing a ReadOnlyCollection instead.

Solution 3

In case you need a List declared as static property

class ListShare 
{
    public static List<String> DataList { get; set; } = new List<String>();
}

class ListUse
{
    public void AddData()
    {
        ListShare.DataList.Add("content ...");
    }

    public void ClearData()
    {
        ListShare.DataList.Clear();
    }
}
Share:
72,482
Brian
Author by

Brian

Updated on July 05, 2022

Comments

  • Brian
    Brian almost 2 years

    can anyone tell me how to create a list in one class and access it from another?

  • Simsons
    Simsons almost 14 years
    @Brian, Create a Object of Foo in the accessing class as Foo objFoo=new Foo(); and then access MyList as List<Item> myList1=objFoo.myList;
  • Brian
    Brian almost 14 years
    Than you for this succinct example.
  • Stanojkovic
    Stanojkovic about 7 years
    Thank you, this is most usefull and helpfull answer!
  • Mecanik
    Mecanik over 6 years
    How does it work? When you call it in another class it will be an empty list.
  • Mecanik
    Mecanik over 6 years
    But each time you do MyClass myClass = new MyClass(); in another class the list is empty again.... how can you access MyClass existing list with content in another class ?
  • aaron lilly
    aaron lilly about 4 years
    i was able to use this answer ,i couldn't quite understand the first, but i did make some changes.
  • aaron lilly
    aaron lilly about 4 years
    class ListUse { public void AddData(string data2add) { ListShare.DataList.Add(data2add); } } class Program{ static void Main(){ Listuse dataAdd = new ListUse(); string data2add = "CONTENT"; ListUse.AddData(data2add);