How to use yield to return expression in C#?
This article will demonstrate yield keyword implementation. I hope it will be useful for all beginners of C#.
This questions is asked in various technical interview questions for experienced candidates those who have more than 6+ years of experience as well.
Description:
It is used in the iterator block which is used to provide a value to the enumerator object.
Yield allows each iteration in a foreach loop be generated only when needed so we can say it is more powerful with for each.
Steps:
1) Create Console application in c#
Put following code in Program.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace YieldDemo
{
class Program
{
static void Main(string[] args)
{
SampleForYield inputValues = new SampleForYield();
foreach (int inputItems in inputValues)
{
Console.WriteLine(inputItems);
}
foreach (string inputItems in inputValues.GetNames())
{
Console.WriteLine(inputItems);
}
}
}
}
2) Create class file SampleForYield.cs and Put following code in that.
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace YieldDemo
{
public class SampleForYield : IEnumerable
{
int[] inputDataNumbers = { 100, 101, 102, 103, 104, 105, 106, 107, 108, 109 };
string[] FirstNameCollections = { "Seema", "Meena", "Hema", "Tina" , "Namita" };
public IEnumerator GetEnumerator()
{
for (int i = 0; i < inputDataNumbers.Length; i++)
{
yield return inputDataNumbers[i];
}
}
public IEnumerable GetNames()
{
for (int i = 0; i < FirstNameCollections.Length; i++)
{
yield return FirstNameCollections[i];
}
Console.ReadLine();
}
}
}