The best answer on this page currently has some flaws that are important to understanding.
As a solution, it is currently written:
public List<Release> Releases { get { return new List<Release>(releases);
It does not work as it is written.
obj.Releases.Add(new Release());
Would affect the base collection by adding a new version to it. . This directly contradicts the stated goal of making the standard procedure private.
However, if you change the public type of the property to implement IEnumerable instead of List and return a version of the ReadOnly list. Such as...
public IEnumerable<Release> Releases { get { return new List<Release>(releases).AsReadOnly(); } protected set { releases = value; } }
Then both
obj.Releases.Add(new Release());
and
obj.Releases = new List<Release>();
will generate build errors and prevent the base collection from being modified.
source share