Search code examples
c#readonly-collection

How to prevent changes to an IReadOnlyList<T>?


I need to use IReadOnlyList<T> as a return parameter since it matches best my needs, but as you can see in the examples below, you can still modify the list it wraps if it is not truly read-only.

using System.Collections.Generic;
using System.Collections.Immutable;

public class Test
{
    public Test()
    {
        // return an IReadOnlyList that wraps a List, we can modify content
        var list1 = GetList1();
        if (list1 is List<Section> sections1) // can be true
        {
            sections1.Clear();
        }

        // return an IReadOnlyList that wraps an ImmutableArray, we cannot modify content
        var list2 = GetList2();
        if (list2 is List<Section> sections2) // never true
        {
            sections2.Clear();
        }
    }

    public static IReadOnlyList<Section> GetList1()
    {
        return new List<Section> {new Section()};
    }

    public static IReadOnlyList<Section> GetList2()
    {
        return ImmutableArray.Create(new Section());
    }
}

public struct Section
{
}

Problem:

ImmutableArray<T> looks great as it is truly read-only, the only thing is I don't want/need to publicly return that fully-featured class that allows changes that produces a copy.

I therefore stick to return IReadOnlyList<T> since it's intent is simple but I need to fix the possibly modifiable list issue.

Question:

Is returning an ImmutableArray<T> as an IReadOnlyList<T> is the right approach ?

If not then can you suggest on how to do it ?


Solution

  • This is not how IReadOnlyList works

    IReadOnlyList Interface

    The IReadOnlyList<T> represents a list in which the number and order of list elements is read-only. The content of list elements is not guaranteed to be read-only.

    If you want an Immutable Collection check out

    System.Collections.Immutable Namespace

    The System.Collections.Immutable namespace contains interfaces and classes that define immutable collections.