Access list from another class

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

+6
scope dictionary list inheritance c #
source share
2 answers
public class MyClass { private List<string> myList = new List<string>(); public List<string> GetList() { return myList; } } 

You can have anything, not a string. Now you can create a MyClass object and access the frontal method in which you implemented return myList.

 public class CallingClass { MyClass myClass = new MyClass(); public void GetList() { List<string> calledList = myClass.GetList(); ///More code here... } } 
+21
source share

To create a list, call the list constructor:

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

To make it available to other classes, add a public property that exposes it.

 class Foo { private List<Item> myList = new List<Item(); public List<Item> MyList { get { return myList; } } } 

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

You may be careful to display lists directly. If you only need to allow read-only access, consider ReadOnlyCollection instead.

+8
source share

All Articles