Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which way of returning a readonly wrapper of List<T> is preferable?

Say, we have a generic class with a private List. We can make it return a readonly wrapper of this list at least with two ways:

public class Test<T>
{
    public List<T> list = new List<T>();

    public IEnumerable<T> Values1
    {
        get
        {
            foreach (T i in list)
                yield return i;
        }
    }

    public IEnumerable<T> Values2
    {
        get
        {
            return list.AsReadOnly();
        }
    }
}

Both Values1 and Values2 reflect any chages in the underlying collection and prevent it from modifying through themselves.

Which way if preferable? What should one be aware of? Or is there any other better way?

like image 361
horgh Avatar asked Oct 02 '12 01:10

horgh


1 Answers

If only an IEnumerable<T> is required for the output, I prefer:

public IEnumerable<T> Values
{
    return this.list.AsReadOnly();
}

Since ReadOnlyCollection<T> implements IEnumerable<T>, this provides a safe wrapper around your objects, while still being flexible and efficient, and preventing a cast from being able to set values.

You can always change the internal implementation later if you decide you need to do something different in the results.

like image 156
Reed Copsey Avatar answered Nov 13 '22 07:11

Reed Copsey