Articles → CSHARP → Yield Keyword In C#
Yield Keyword In C#
Purpose
using System;
using System.Collections.Generic;
namespace Yield_Sample {
class Program {
static void Main(string[] args) {
Program prog = new Program();
foreach(int i in prog.ReturnList())
Console.WriteLine(i);
Console.ReadLine();
}
public IEnumerable < int > ReturnList() {
int count = 10;
int[] coll = new int[count];
for (int i = 1; i <= count; i++) {
coll[i - 1] = i;
}
return coll;
}
}
}
Click to Enlarge
using System;
using System.Collections.Generic;
namespace Yield_Sample {
class Program {
static void Main(string[] args) {
Program prog = new Program();
foreach(int i in prog.ReturnList())
Console.WriteLine(i);
Console.ReadLine();
}
public IEnumerable < int > ReturnList() {
int count = 10;
for (int i = 1; i <= count; i++) {
yield
return i;
}
}
}
}
- We are not using any temporary list variable to store the values.
- One value is returned at a time instead of the whole collection.
Important Point Regarding Yield Keyword
- You cannot return yield statement in try-catch block.
- You cannot return out or ref parameters using yield keyword.
- You cannot use yield statement inside anonymous method.
- You cannot use yield statement inside unsafe method.