C # Return private objects

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()
  {
    // 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 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?

+3
source share
6 answers

Return 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 clearly a read-only type.

@Freed, , , Foo.

, (, , ):

public ReadOnlyCollection<Bar> DoSomething()
{
  // Add items to the list
  return new ReadOnlyCollection<Bar>(new List<Bar>(_myList));
}
+7

, , ReadOnlyCollection, .

. , .

+2

_myList, , : ?

,

  • ReadOnlyCollection<T>
  • IEnumerable<T> (, , List<T>)
  • .ToList()
  • ctor List<T>

ReadOnlyCollection<T>, -, . , , readonly... .

, !

+1

return new List<Bar>(_myList);

? - ;)

0

, ReadOnlyCollection<T> - . (.NET)

0
0

Source: https://habr.com/ru/post/1773212/


All Articles