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?