Sometimes you have class which contains a list, defined as a member variable of type List<T>. You need to expose the contents of the list via property or method.
One option is to simply return the list itself. In the following example, see the Names property which returns the list itself.
using System.Collections.Generic; class NameList1 { private List<string> m_names; public NameList1() { m_names = new List<string>(); m_names.Add("Enrico"); m_names.Add("Gertrude"); m_names.Add("Humperdink"); } public List<string> Names { get { // Return the names. return m_names; } } }
The problem with this is that your callers can modify your list.
NameList1 names1 = new NameList1(); names1.Names.Add("Foo!!!");
One solution is to modify the class so that it returns a copy of the list:
using System.Collections.Generic; class NameList2 { private List<string> m_names; public NameList2() { m_names = new List<string>(); m_names.Add("Enrico"); m_names.Add("Gertrude"); m_names.Add("Humperdink"); } public List<string> Names { get { // Return a copy of the list. return new List<string>(m_names); } } }
This way the Names property returns a copy of the original list. Callers can still call the Add(), Remove(), Clear() etc methods on the list that is returned, but they will only be affecting the copy. While this prevents external code from modifying the data in your class, it is not very clear that this was your intention.
A better solution is to use the System.Collections.ObjectModel.ReadOnlyCollection<T> class:
using System.Collections.Generic; using System.Collections.ObjectModel; class NameList3 { private List<string> m_names; public NameList3() { m_names = new List<string>(); m_names.Add("Enrico"); m_names.Add("Gertrude"); m_names.Add("Humperdink"); } public ReadOnlyCollection<string> Names { get { // Return a read only collection containing the items in the list. return new ReadOnlyCollection<string>(m_names); } } }
Returning a read-only collection as shown here prevents other code from modifying your list, and at the same time makes your intentions clear.