Hi, can anyone tell me how to create a list in one class and access it from another?
A:
Assuming that you don't need inheritance between classes.
Class A
{
public A()
{
Mylist = new List<string>();
}
public List< string > Mylist {get;set;}
}
Class B
{
private A = defaut(A);
public B()
{
A obj = new A();
obj.MyList.Add("Temp");
}
}
saurabh
2010-09-15 11:15:44
+4
A:
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.
Mark Byers
2010-09-15 11:16:19
Thanks Mark. Sorry to sound simple but could you show me an example of how you access myList from another class?
Brian
2010-09-15 11:29:33
@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;
Subhen
2010-09-15 11:44:39
+7
A:
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 pubic 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...
}
}
sumit_programmer
2010-09-15 11:35:33