Search This Blog

Saturday, July 16, 2011

Yield Examples

Yield
 Purpose of yield is to control sequence of loop.This can be used with in iterator (looping),implementing in the body of loop.
yield return inside a method as  IEnumerator object.

Syntax:
AccessModifier static IEnumerator<Datatype> Methodname()
{
/*-----To do something---*/

yield return "whatever you return"; eg: yield return strname;
}


Example:

int iNum=0;
int iResult;
foreach(int i in GetNumber())
{
        iResult=iNum+i;
}


private static IEnemurator<int> GetNumber()
{
   for(int i =0; i<10;i++)
  {
      yield return i;
  }
}

Explanation:
This is sum of series example here ,we call Getnumber method for get a i value. After call a Getnumber method.First i value is zero  return, then i add with iNum,then  continue Getnumber method until i reaches ten.
Note:
Yield return  a value only IEnumerator object.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.