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;
}
}
}
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;
}
}
}
}
- It avoids using a temporary list to store intermediate values.
- It simultaneously returns one value at a time instead of the entire collection.
Important Point Regarding The Yield Keyword
- You cannot return a yield statement in a try-catch block.
- You cannot return out or ref parameters using the yield keyword.
- You cannot use the yield statement inside an anonymous method.
- You cannot use the yield statement inside the unsafe method.
Posted By - | Karan Gupta |
|
Posted On - | Tuesday, August 28, 2018 |