Thursday 2 April 2015

Use of c# “Yield” keyword ?

Yield is one of the most useful but under-used keywords in C#. The reason is that most of us don't even know about this keyword and the purpose it can serve for us.

The functionality provided by Yield keyword is that when iterating a list, we can read an element of the loop, return to the calling code and go back to the loop again at the same point, from where it left the loop and continue processing the records in the loop. So this will be the basic idea behind the example that we will be using. 

Scenario where “yield” keyword is useful:-
Customized iteration through a collection without creating a temporary collection.

    Let’s try to understand what customized iteration means with an example.  
Consider the below code.
Let say we have a simple list called as “MyList” which has collection of 5 continuous numeric values 1,2,3,4 and 5. This list is browsed/iterated from console application from within static void main method.

static List<intMyList = new List<int>();
static void FillValues()
{
            MyList.Add(1);
            MyList.Add(2);
            MyList.Add(3);
            MyList.Add(4);
            MyList.Add(5);
}
static void Main(string[] args// Caller
{
            FillValues(); // Fills the list with 5 values
            foreach (int i in MyList// Browses through the list
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
}

Now let me complicate this situation let’s say the caller only wants values greater than “3” from the collection. So the obvious thing as a c# developer we will do is create a function as shown below. This function will have temporary collection. In this temporary collection we will first add values which are greater than “3” and return the same to the caller. The caller can then iterate through this collection.

static IEnumerable<intFilterWithoutYield()
{
            List<inttemp = new List<int>();
            foreach (int i in MyList)
            {
                if (i > 3)
                {
                    temp.Add(i);
                }
            }
            return temp;
}

Now the above approach is fine but it would be great if we would get rid of the collection, so that our code becomes simple. This where “yield” keyword comes to help. Below is a simple code how we have used yield.
Yield” keyword will return back the control to the caller, the caller will do his work and re-enter the function from where he had left and continue iteration from that point onwards. In other words “yield” keyword moves control of the program to and fro between caller and the collection.

static IEnumerable<intFilterWithYield()
{
            foreach (int i in MyList)
            {
                if (i > 3yield return i;
            }
}

So for the above code following are details steps how the control will flow between caller and collection. 
  • Caller calls the function to iterate for number’s greater than 3.
  • Inside the function the for loop runs from 1 to 2 , from 2 to 3 until it encounters value greater than “3” i.e. “4”. As soon as the condition of value greater than 3 is met the “yield” keyword sends this data back to the caller.
  • Caller displays the value on the console and re-enters the function for more data. This time when it reenters, it does not start from first. It remembers the state and starts from “5”. The iteration continues further as usual.

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives