C# Encapsulate ArrayList
Listing 3. This is the second version of the MRU class. In this version, you control access to the internal ArrayList object tightly because you encapsulate it. ![]() using System; using System.Collections; namespace MRUProject { public class MRU { private ArrayList items = new ArrayList(6); public MRU() {} public object this[short i] { get { if ((i < 0) || (i >= Count)) { throw new ArgumentOutOfRangeException("MRU index must be above 0 and less than the current count."); } return items[(int)i]; } } public IEnumerator GetEnumerator() { return items.GetEnumerator(); } public bool Contains(object obj) { return items.Contains(obj); } public void Add(object obj) { if (items.Contains(obj)) items.Remove(obj); else if (Count == Capacity) items.RemoveAt(Count - 1); items.Insert(0,obj); } public void Remove(object obj) { items.Remove(obj); } public void Clear() { items.Clear(); } public int Count { get { return items.Count; } } public int Capacity { get { return items.Capacity; } set { if (value > 10) throw new ArgumentOutOfRangeException("Capacity", "Maximum size of the MRU is 10"); items.Capacity = value; } } } } |