MyITBlog.com - IT Professionals Online Journal
 
  Home  |   Site News  |   About Us  |   Privacy  |   FAQ  |   Contact   Add Blog Entry  |  Login  |  Register   
 My Account
Username
Password
Remember me
Lost Password?


 Categories


  HOME  >  Programming  >  MicrosoftPrint


0
Votes
Iterators in C# 2.0 in Microsoft   
by sundararajan on 20 Nov 2005, 01:32     Read sundararajan's Blog
Total Hits: 634    Comments: 0   

Why Iterators?

    As developers, many would have enjoyed the flexibility offered by foreach statements in C# .earlier to enumerate our enumerable collections using the foreach statements, the Ienumerable interface had to be implemented completely.

 

   In C#2.0 , Iterators have come to the rescue of the developers to make the class enumerable using foreach without implementing much of Ienumerable interface.

 

Iterators – what it is?

Iterator is a section of code that returns an ordered sequence of values of the same type.

 

Yield Statement:

 

   A new statement construct called ‘Yield’ has been introduced in C# 2.0 that plays a major role in building simple enumerable collections.

  Yield is used in an iterator block to provide value to an enumertor object or to signal the  end of an iteration.

 

Yield takes any of the following two forms.

 

      yield return expression;

      yield break;

 

Iterator Sample:

 

   The common method to implement iterators is to implement the GetEnumerator method in Ienumerable interface.

 

The sample is as below.

<><><><><> 

 

 

 

 

 

Iterators- Implementing IEnumerator.GetEnumerable

class IteratorSample    {

        public System.Collections.IEnumerator GetEnumerator()

        {           for (int i = 0; i < 10; i++)

            {

                yield return i;

                      }

        }

         static void Main(string[] args)

        {

            IteratorSample objIteratorSample = new IteratorSample();

            foreach (int i in objIteratorSample)

                Console.WriteLine(i);

        }

    }

 

 

 

Named Iterators:-

 

 

Named iterators are a means to provide multiple iterators for the same collection of data. An iterator can be provided with parameters also when using Named iterators.  

 

 

Here System.Collections.IEnumerable Interface is used as a return type for the named iterator whereas Ienumerator interface is used for implementing GetEnumerator() method.

Refer to the code download please..... 

 

 

 

 

 

 

 

 

 


 

Post Comment

Copyright © 2008 MyITBlog.com