Improve your C# with YIELD
Tags: dotnet, csharp, beginners
Published: 2022-12-10 17:18:37

## Explanation

The yield keyword in C# is used to create an iterator method, which allows the programmer to loop through a collection of items, one at a time. It allows the code inside the iterator method to "yield" each item in the collection, one at a time, rather than returning the entire collection all at once. This can be useful when working with large collections of data, as it allows the programmer to process the data one item at a time, rather than having to load the entire collection into memory all at once.

## Example

Here is an example of how the yield keyword can be used to create an iterator method in C#:

```
public static IEnumerable<int> GetOddNumbers(int start, int end)
{
    for (int i = start; i <= end; i++)
    {
        if (i % 2 != 0)
        {
            yield return i;
        }
    }
}
```

In this example, the GetOddNumbers method is an iterator method that takes a starting and ending integer as arguments, and yields all of the odd numbers between the starting and ending integers. The yield return statement is used to "return" each odd number in the range to the caller of the method, one at a time.

To use this iterator method, you could write code like this:

```
foreach (int oddNumber in GetOddNumbers(1, 10))
{
    Console.WriteLine(oddNumber);
}
```

This code would use the foreach loop to iterate over each odd number yielded by the GetOddNumbers iterator method, and print each one to the console.

## USE CASES

 - When working with large collections of data

When working with large collections of data, such as a large list of database records or a large file containing multiple records, using the yield keyword can allow the programmer to process the data one record at a time, rather than having to load the entire collection into memory all at once. This can help to improve the performance and scalability of the application.


```
public static IEnumerable<DatabaseRecord> GetDatabaseRecords()
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        var command = new SqlCommand("SELECT * FROM Records", connection);
        var reader = command.ExecuteReader();
        while (reader.Read())
        {
            yield return new DatabaseRecord(reader);
        }
    }
}
```

In this example, the GetDatabaseRecords method is an iterator method that yields each DatabaseRecord from a database query one at a time, rather than returning the entire collection of records all at once. This can help to improve the performance and scalability of the application, as it allows the records to be processed one at a time, rather than having to load the entire collection into memory all at once.

- When working with infinite sequences or streams of data:

When working with infinite sequences or streams of data, such as a continuous stream of incoming network traffic or sensor readings, the yield keyword can be used to create an iterator method that yields each piece of data in the sequence as it becomes available, rather than having to wait for the entire sequence to be generated before processing it.

```
public static IEnumerable<SensorReading> GetSensorReadings()
{
    while (true)
    {
        yield return sensor.GetNextReading();
    }
}
```

In this example, the GetSensorReadings method is an iterator method that yields each SensorReading from a sensor as it becomes available, rather than having to wait for the entire sequence of readings to be generated before processing them. This allows the application to process the sensor readings as they are generated, rather than having to wait for the entire sequence to be generated before processing it.

- When working with algorithms that generate sequences of data:

When working with algorithms that generate sequences of data, such as algorithms that generate sequences of random numbers or prime numbers, the yield keyword can be used to create an iterator method that yields each element in the generated sequence as it is produced, rather than having to generate the entire sequence at once and return it to the caller.

```
public static IEnumerable<int> GetRandomNumbers(int min, int max)
{
    Random random = new Random();
    while (true)
    {
        yield return random.Next(min, max);
    }
}
```

In this example, the GetRandomNumbers method is an iterator method that yields a sequence of random numbers. The yield return statement is used to "return" each random number in the sequence as it is generated, rather than generating the entire sequence at once and returning it to the caller. This allows the application to process the random numbers as they are generated, rather than having to wait for the entire sequence to be generated before processing it.

Please check out my Youtube channel for more C# and .NET content.

https://www.youtube.com/channel/UCfZF4WWaH4i13MzEICLt6sQ