How to

use yield return keyword

Published: 14. October 2011 | Updated: 14. October 2011
License: Microsoft Public License (MS-PL)
Categories: Collections
Tags: C# Collections
Was this snippet helpful for you? YESYES / NONO

Import namespace

using System.Collections.Generic;

Method which using yield

public IEnumerable<string> GetDataUsingYield()
{
    Console.WriteLine("-> Method start");
    yield return "A";
    yield return "B";
    yield return "C";
    yield return "D";
    yield return "E";
    yield return "F";
    Console.WriteLine("-> Method finished");
}

Use

Console.WriteLine("Going to call method with yield");

IEnumerable<string> data = GetDataUsingYield();

Console.WriteLine("Method call finished");
Console.WriteLine();

foreach (string s in data)
{
    Console.WriteLine(s);
}
Console Output:
Going to call method with yield
Method call finished

-> Method start
A
B
C
D
E
F
-> Method finished
Send us feedback about this snippet »



Related Snippets: