Tuesday, February 8, 2011

What is the use of yield keyword in C#?


Yield keyword is used in an iterator block to calculate the value for the enumerator object.

An iterator is a method,
get accessor, or operator that allows us to use foreach loop on object references of user-defined classes.

yield keyword can be used as:

1)yield return ;
or
2)yield break;


code snippet

using System;

//This namespace provides the IEnumerator interface

using System.Collections;

public class demo

{

//GetEnumerator method of IEnumerable interface creates the iterator

public IEnumerator GetEnumerator()

{

for (int i = 1; i <=5; i++)

{

yield return i;

}

}





static void Main()

{



demo t=new demo();



//foreach loop calls the GetEnumerator method

foreach (int i in t)

{

Console.WriteLine(i);

}

}

}


output:

1
2
3
4
5

Found interesting?