How to make the class as an IEnumerable in C#?
c#, class, ienumerable
Solution
Implement the interface IEnumerable:
class Contacts : IEnumerable<Contact>
{
List<Contact> contacts;
#region Implementation of IEnumerable
public IEnumerator<Contact> GetEnumerator()
{
return contacts.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
Problem
So I've got a class and a generic List inside of it, but it is private. ``` class Contacts { List<Contact> contacts; ... } ``` I want to make the class work as this would do: ``` foreach(Contact in contacts) .... ; ``` like this (not working): ``` Contacts c; foreach(Contact in c) .... ; ``` In the example above the Contact class instance c has to yield return every item from contacts(private member of c) How do I do it? I know it has to be IEnumerable with yield return, but where to declare that?