Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks?