Search code examples
c#collectionsgeneric-collections

C# readonly access to List<> or other collection, or ToArray() magic


1st question is about way of protecting my List from changing(remove/add/clear etc...) from outside

there is my way:

class Foo 
{
    public int[] MyCollection
    {
        get{ return (_myCollection==null)?null:_myCollection.ToArray();
    }
    protected List<int> _myCollection;
}

Is it good? Or is there any better ideas, or may be patterns?

2nd: When iam testing this solution with stopwatch, i was very surprised.

List -enumeration was slower than List.ToArray() enumeration with cast time:

List<int> myList = new List<int>();
for (int j = 0; j < 10000; j++)
{
    myList.Add(j);
}
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000; i++)
{
    //casting every iteration:
    var ROC = myList.ToArray();
    int count = 0;
    foreach (var a in ROC)
    {
        count += a;
    }
}
sw.Stop();
Console.WriteLine(sw.Elapsed);

It shows me 700 msec, and

List<int> myList = new List<int>();
for (int j = 0; j < 10000; j++)
{
    myList.Add(j);
}
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000; i++)
{
    int count = 0;
    //No casting at all
    foreach (var a in myList)
    {
        count += a;
    }
}
sw.Stop();
Console.WriteLine(sw.Elapsed);

Shows me 843 msec... why is it so?


Solution

  • For read only collection you could use List<T>.AsReadOnly()

    public IList<int> MyCollection
    {
       get{ return _myCollection==null  ? null : _myCollection.AsReadOnly();
    }
    

    If necessary and in order to make more clear that we're talking about a read only collection you could define your property like this

    public IReadOnlyList<int> MyCollection