Search code examples
c#dictionarycollectionsreadonly-collection

Readonly List<Dictionary<>>


If we have field List<Dictionary<>>, how to expose it as a readonly property?

To example:

public class Test
{
    private List<Dictionary<string, object>> _list;
}

I can expose it like this

public ReadOnlyCollection<Dictionary<string, object>> List
{
    get { return _list.AsReadOnly(); }
}

but it is still possible to change directory:

var test = new Test();
test.List[0]["a"] = 3; // possible
test.List[0].Add("e", 33); // possible

Here is an attempt to make it readonly

public ReadOnlyCollection<ReadOnlyDictionary<string, object>> List
{
    get
    {
        return _list.Select(item =>
            new ReadOnlyDictionary<string, object>(item)).ToList().AsReadOnly();
    }
}

I think the problem with this approach is obvious: it's a new list of new dictionaries.

What I would like to have is something similar to List<>.AsReadOnly(), to have property act as a wrapper over _list.


Solution

  • If you cannot create a new list of Dictionary objects, I would suggest to expose the items that you need from your class directly:

    public IReadOnlyDictionary<string, object> this[int i] 
    {
        get { return this._list[i]; }
    }
    //OR
    public IReadOnlyDictionary<string, object> GetListItem(int i)
    {
        return _list[i];
    }
    
    public int ListCount
    {
        get { return this._list.Count; }
    }  
    

    Then use it like this:

    var test = new Test();
    
    var dictionary = test[0];
    //OR
    dictionary = test.GetListItem(0);
    
    int count = test.ListCount;