In the below code I have created one method to print values using Yield and another just a simple list iteration. So here my question is the output obtained from both the methods are same so why do we go for Yield keyword? and also please tell me the exact usage of Yield keyword in application.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YieldKeyWordEg
{
class Program
{
static void Main(string[] args)
{
Animals obj = new Animals();
Console.WriteLine("------ Using Yield ------");
foreach (var item in obj.GetName())
{
Console.WriteLine(item);
}
Console.WriteLine("------ Using List Iteration ------");
foreach (var items in obj.GetNameinList())
{
Console.WriteLine(items);
}
Console.ReadLine();
}
}
class Animals
{
public IEnumerable<string> GetName()
{
List<string> objList = new List<string>();
objList.Add("Cow");
objList.Add("Goat");
objList.Add("Deer");
objList.Add("Lion");
foreach (var item in objList)
{
yield return item;
}
}
public List<string> GetNameinList()
{
List<string> objList = new List<string>();
objList.Add("Cow");
objList.Add("Goat");
objList.Add("Deer");
objList.Add("Lion");
return objList;
}
}
}
Output:
------ Using Yield ------
Cow
Goat
Deer
Lion
------ Using List Iteration ------
Cow
Goat
Deer
Lion