Reputation: 578
I have a class A
that contains a List
field.
public class A
{
public List<int> list = new List<int>();
}
I would like to remove an element from the list
from class B
without making the list in class A
static
. How can I do that?
Upvotes: 1
Views: 413
Reputation: 22553
If you don't mind instantiating it, it's simply
A a = new A();
a.list...
If you don't want to instantiate a new one, you can pass an existing instance to B on its constructor:
public class B{
private A myA;
public B( A a) {
this.myA = a;
}
public doSomething(){
this.myA....
}
}
Now you can use A as a field of B.
Upvotes: 1
Reputation: 3454
A more OOP solution for this problem would be:
public class A
{
private List<int> list = new List<int>();
List<int> getList();
void setList(List<int> list);
}
Then in the code where it is used,
A a = new A();
List<int> list = a.getList();
modify list as you want
a.setList(list);
Upvotes: 1
Reputation: 39946
You could create an instance of class A
inside a method in class B
. Then you could access the list
field, like this:
public class B
{
void method()
{
A a = new A();
int item = 2;
a.list.Remove(item);
}
}
Upvotes: 6