Saturday, 2 June 2012

How to use yield in .net, How it is implemented in .net?


yield :  yield is a keyword 

yield return within a method that returns IEnumerable or IEnumerator the language feature is activated.

We know Interface base IEnumerable iteration is thread safe iteration which is done by making use of yield keyword.
Array implements the IEnumerable, or IEnumerable<T> so every array type is iterated through a safe thread.
In  
  int[] intarr={10,20,30};
            IEnumerator iers = intarr.GetEnumerator();
            while (iers.MoveNext())
            {
                int s = (int)iers.Current;
                Console.Write(s);
            }
Output: 10 20 30
This is thread safe iteration we are not using any where yield keyword.why because Array implements yield keyword in side GetEnumerator() method.
Like below:

class EnumerableDemo               // Like IEnumerable
    {
        public static IEnumerable<int> GetInt()  // like GetEnumerator
        {
            for (int i = 0; i < 5; i++)
                yield return i;
        }
      
        static void Main()
        {                       
           IEnumerable<int> ier = AsEnumerableDemo.GetInt();
           IEnumerator<int> s=ier.GetEnumerator();                        
            int j = ier.Count<int>();
            Console.Write(j);
            Console.Read();

        }
Output : 5

So whenever we return multiple values as same type use IEnumerable<Type> as return type.

Now how Microsoft .net implements IEnumerable<int> in Aarry type.

   class ArrayClass : IEnumerable<int>
    {
     
        public IEnumerator<int> GetEnumerator()
        {
            for (int i = 1; i < 15; i++)
                yield return i;
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }    
    }
class SafeEnumerableDemo
    {              
        static void Main()
        {
            ArrayClass tobj = new ArrayClass();
            IEnumerator iob = tobj.GetEnumerator();
            while (iob.MoveNext())
            {
                int k = (int)iob.Current;
                Console.Write(k);
            }     
            Console.Read();
        }       
    }


No comments:

Post a Comment