Skip to content
Bradley Grainger edited this page Jan 1, 2019 · 3 revisions

Avoid ToReadOnlyCollection in constructors

The ReadOnlyCollection<T> returned by Libronix.Utility.EnumerableUtility.ToReadOnlyCollection does not guarantee that a new read-only collection is created; it may just return a wrapper around an existing List<T>.

The following pattern in a constructor is dangerous because it may save a reference to a List<T> that a caller could modify:

public class Data
{
    public Data(IEnumerable<T> values)
    {
        Values = values.ToReadOnlyCollection();
    }

    public ReadOnlyCollection<T> Values { get; }
}

Suggested Fixes

  • Use .ToList().AsReadOnly() to force a new, private List to be created.
Clone this wiki locally