Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top