Implementing IEnumerable in C#


IEnumerable is the base interface for all collections that can be enumerated.

IEnumerable contains a single method, GetEnumerator, which returns an IEnumerator. IEnumerator provides the ability to iterate through the collection by exposing a Current property and MoveNext and Reset methods.

It is a best practice to implement IEnumerable and IEnumerator on your collection classes to enable the foreach statement.

Example program for IEnumerable in C#.NET

 

using System;

using System.Collections;

namespace ProgramCall

{

class person : IEnumerable

{

private int[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

public int Age { get; set; }

public string Name { get; set; }

#region IEnumerable Members

public IEnumerator GetEnumerator()

{

return list.GetEnumerator();

}

#endregion

}

class MainClass

{

static void Main(string[] args)

{

person personobj = new person();

foreach(var n in personobj)

{

Console.WriteLine(n);

}

Console.Read();

}

}

}


Zooming in Winforms Webbrowser Control in .NET
Filtering Datatable with Select Conditions and Sorting in C#.NET
Hiding a property from displaying in Datagridview in C#.NET
Logic to detect if Application is started from Citrix/Terminal Server/PC in C#
Winforms Application.DoEvents Method
Modify XML file with tagname in c#.net
Read Machine IP Address in C#
Check if IIS is running using C#
Built in Delegates in .NET Framework
Changing Winform webbrowser control IE version in C#.NET
Set the dropdown width of any combobox based on the data
Difference between Const and ReadOnly
Example for Property Change Notification in C#.NET
Example Program using Delegates and Events in C#
AutoComplete in .NET Winforms TextBox
How to read data from XML String and insert in to table in SQL Server
WebBrowser.navigate Data Submission by Get or Post Methods
Datagridview Paging
Copy Datagridview cell value using ContextMenu
Inserting data in Datatable in C#
Cookie in .NET
Using Control's Child Index and Dock property for achieving desired layout in a form.
Accessing section group inside configuration of web.config
Create File in .NET C#
Change button shape in .net
Dispose vs Finalize in .net




Implementing IEnumerable, IEnumerable and IEnumerator in .net, foreach in c#.net