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?
Return a new ReadOnlyCollection:
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(_myList);
}
This is a wrapper for the list and the type is explicitly a read only type.
As @Freed notes, this is not thread safe, as it is only a wrapper and the list can change within the Foo class.
For better thread safety, make a copy before returning it (though if this is a requirement you should design the class for that to begin with):
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(new List<Bar>(_myList));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With