The IEnumerable interface appears in C# programs. Which specifies that the underlying type implements GetEnumerator method to innumerate the object bind for collection. It enables the foreach-loop to be used.
In many case we need to implement the IEnumerable interface on the base class so once we are inheriting the base class which should have the enumerable functionality.
Please find the below code to implement the IEnumerable
public class BasePage<T> : IEnumerable<T&>
{
List<T> _arraList;
static int _currPos = 0;
public BasePage()
{
_arraList = new List<T>();
_currPos = 0;
}
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
foreach (T item in _arraList)
{
yield return item;
}
}
//public IEnumerator<T> GetEnumerator()
//{
// for (int i = 0; i <= _currPos; i++)
// yield return _arraList[i];
//}
#endregion IEnumerable<T> Members
#region IEnumerable<T> Members
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _arraList.GetEnumerator();
}
#endregion IEnumerable<T> Members
#region IEnumerable Members
//IEnumerator IEnumerable.GetEnumerator()
//{
// for (int i = 0; i <= _currPos; i++)
// yield return _arraList[i];
//}
IEnumerator IEnumerable.GetEnumerator()
{
yield return this;
}
#endregion IEnumerable Members
internal void Add(T Item)
{
_arraList.Add(Item);
}
}
Now use that base class implementation to one of the derived class like below;
public class Employee : BasePage<Employee>
{
public string Name { get; set; }
public string Designation { get; set; }
}
Assigning the object value to the derived class;
class Program
{
static void Main(string[] args)
{
BasePage<Employee> objcol = new BasePage<Employee>();
objcol.Add(new Employee { Name = "John", Designation = "manager" });
objcol.Add(new Employee { Name = "BOb", Designation = "Worker" });
objcol.Add(new Employee { Name = "Eric", Designation = "Worker" });
}
}
No comments:
Post a Comment