Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the class as an IEnumerable in C#?

Tags:

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?

like image 750
Ivan Prodanov Avatar asked Oct 30 '12 08:10

Ivan Prodanov


People also ask

How use IEnumerable method in C#?

IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator. If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).

What is IEnumerable <> in C#?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.


1 Answers

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 } 
like image 164
LightStriker Avatar answered Oct 26 '22 17:10

LightStriker