Are there any recommendations for returning a class object? I have a class that has a List and a method that does something with a list and returns this list:
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
return _myList;
}
}
I donβt think this is a good way to return the list, because now the calling method can change the list, and thus the list in the Foo object is updated. This can lead to unexpected and unwanted behavior.
How do you deal with such situations? You make a copy of the object (in this case, the list) and return that object or ...? Are there any recommendations or tricks?
source
share