Yield Is Fundamental For Lazy/Deffered execution

Let’s understand the problem using Client and Server classes

class Server
{        
   Random r = new Random();
   public void IterateNumber()
   {
      List integerList = Enumerable.Range(1,1000).ToList();
      foreach (var item in integerList)
      {
          int ProcessedNumber = ApplyProcess(item);
          Console.WriteLine("Process Number:{0}", ProcessedNumber );
      }                    
   }
   public int ApplyProcess(int num)
   {      
      r.Next(1, 10);
      return num * r.Next(1, 10);
   }
}

class Client
{
   Server serv = new Server();
   public void Execute()
   {
      serv.IterateNumber();
   }
}

Food For Thought

Server class processes each number nothing bad in that, but can client evaluate processed number and decide to stop at certain value

Does Client class has right to do that ???  To answer this question “YES”,  Yield  Keyword comes into the picture

In simple words yield return hold further iteration and return value to client to make decision to iterate further or not

class Server
{
   Random r = new Random();
   public IEnumerable IterateNumber()
   {
      List integerList = Enumerable.Range(1,1000).ToList();
      foreach (var item in integerList)
      {
          int ProcessedNumber = ApplyProcess(item);
          Console.WriteLine("Process Number:{0}", ProcessedNumber );
          yield return ProcessedNumber;
      }                    
   }
   public int ApplyProcess(int num)
   {            
      r.Next(1, 10);
      return num * r.Next(1, 10);
   }
}

class Client
{
   Server serv = new Server();
   public void Execute()
   {
      IEnumerable ienum = serv.IterateNumber();
      foreach (var item in ienum)
      {
          if ((int)item == 100)
          {
              break;
          }
      }
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s