I believe some of you already know about this but for me I never used it. Yield keyword has been existed since .NET 2.0 so I decided to look up of what it does and try to understand it
Based on MSDN
Yield is used in an iterator block to provide a value to the enumerator object or to signal the end of iteration, it takes one of the following form
Based on my understanding
Yield is a concatenation for a collection, or in SQL we normally use UNION
Yield break; is used to exit from the concatenation (remember it is not used to skip !)
One practical sample that I can think of is to get the enumerable of exception from inner exception (e.g stack trace)
sample code
- class Program
- {
- ///<summary>
- /// simple function to return IEnumerable of integer
- ///</summary>
- ///<returns></returns>
- private static IEnumerable<int> GetIntegers()
- {
- for (int i = 0; i <= 10; i++)
- yield return i;
- }
- ///<summary>
- /// simple function to return collection of class
- ///</summary>
- ///<returns></returns>
- private static IEnumerable<MyClass> GetMyNumbers()
- {
- for (int i = 0; i <= 10; i++)
- if (i > 5)
- yield break;
- else
- yield return new MyClass() { Number = i };
- }
- internal class MyClass
- {
- public int Number { get; set; }
- public string PrintNumber
- {
- get {
- return “This is no “ + Number.ToString();
- }
- }
- }
- static void Main(string[] args)
- {
- Console.WriteLine(“Simple array of integer”);
- foreach (var number in GetIntegers())
- Console.WriteLine(number.ToString());
- Console.WriteLine();
- Console.WriteLine(“Collection of classes”);
- foreach (var myclass in GetMyNumbers())
- Console.WriteLine(myclass.PrintNumber);
- Console.ReadLine();
- }
- }
Output
0
1
2
3
4
5
6
7
8
9
10Collection of classes
This is no 0
This is no 1
This is no 2
This is no 3
This is no 4
This is no 5
Leave a Reply