Access List from another class
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();
}
}
Brian
Updated on July 05, 2022Comments
-
Brian almost 2 years
can anyone tell me how to create a list in one class and access it from another?
-
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 almost 14 yearsThan you for this succinct example.
-
Stanojkovic about 7 yearsThank you, this is most usefull and helpfull answer!
-
Mecanik over 6 yearsHow does it work? When you call it in another class it will be an empty list.
-
Mecanik over 6 yearsBut 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 about 4 yearsi was able to use this answer ,i couldn't quite understand the first, but i did make some changes.
-
aaron lilly about 4 yearsclass 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);