1

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?

2
  • Why do you need to make it static? you set it to public so anyone with an instance of class A can already get to list and modify it. Commented Jun 27, 2016 at 11:39
  • create class A object in class B to access the list Commented Jun 27, 2016 at 11:40

3 Answers 3

6

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); } } 
Sign up to request clarification or add additional context in comments.

Comments

1

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); 

Comments

1

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.

1 Comment

How can i pass it to B?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.