An iterator is a method, get accessor or operator that enables you to support foreach iteration in a class or structure without implementing the entire ienumerable interface. You only need to provide an iterator to traverse the data structure in the class. When the compiler detects the iterator, it automatically generates the current, movenext, and dispose methods for the ienumerable or ienumerable <t> interfaces. An iterator is a sequence that can return values of the same type.Code. The iterator can be used as a method, operator, or get accessors code body. The iterator Code uses the yield return statement to return each element in sequence. Yield break terminates iteration. Multiple iterators can be implemented in the class. Each iterator must have a unique name like any class member and can be called by client code in the foreach statement, as shown below: foreach (int x in sampleclass. iterator2 ){} The return type of the iterator must be ienumerable, ienumerator, ienumerable <t>, or ienumerator <t>.
Public Class Daysoftheweek: system. Collections. ienumerable { String [] M_days = { "Sun" , "Mon" , "Tue" , "Wed" , "Thr" , "Fri" ,"Sat" }; Public System. Collections. ienumerator getenumerator (){ For ( Int I = 0; I <m_days.length; I ++ ){ Yield Return M_days [I] ;}} Class Testdaysoftheweek { Static Void Main () {daysoftheweek week = New Daysoftheweek (); Foreach (String Day In Week) {system. Console. Write (day + "" );}}} |