collections/collection/naive/simple.cs - A collection of up to three instance variables of type T - with an iterator. | Lecture 12 - slide 35 : 36 Program 1 |
using System; using System.Collections.Generic; using System.Collections; public class GivenCollection<T> : IEnumerable<T>{ private T first, second, third; private bool firstDefined, secondDefined, thirdDefined; public GivenCollection(){ this.firstDefined = false; this.secondDefined = false; this.thirdDefined = false; } public GivenCollection(T first){ this.first = first; this.firstDefined = true; this.secondDefined = false; this.thirdDefined = false; } public GivenCollection(T first, T second){ this.first = first; this.second = second; this.firstDefined = true; this.secondDefined = true; this.thirdDefined = false; } public GivenCollection(T first, T second, T third){ this.first = first; this.second = second; this.third = third; this.firstDefined = true; this.secondDefined = true; this.thirdDefined = true; } public int Count(){ int res; if (!firstDefined) res = 0; else if (!secondDefined) res = 1; else if (!thirdDefined) res = 2; else res = 3; return res; } public IEnumerator<T> GetEnumerator(){ if (firstDefined) yield return first; if (secondDefined) yield return second; // not else if (thirdDefined) yield return third; // not else } IEnumerator IEnumerable.GetEnumerator(){ return GetEnumerator(); } }