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?
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).
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With