---
title: "What is the use of the yield keyword in C#?"  
description: "What is the use of the yield keyword in C#?"  
author: "Steilla Mitchel"  
published: 2023-07-12  
updated: 2023-07-13  
canonical: https://www.mindstick.com/forum/159057/what-is-the-use-of-the-yield-keyword-in-c-sharp  
category: "c#"  
tags: ["c#", "keyword research"]  
reading_time: 1 minute  

---

# What is the use of the yield keyword in C#?

What is the use of the yield [keyword in C#](https://www.mindstick.com/forum/253/difference-between-ref-and-out-keyword-in-c-sharp)?

## Replies

### Reply by Aryan Kumar

The `yield` [keyword](https://www.mindstick.com/forum/33572/sql-inner-join-keyword) in C# is used to create iterators. An iterator is a method that can be used to iterate over a collection of data. The `yield` keyword allows you to create iterators that can be used to iterate over collections that are not fully loaded into memory.

For example, the following code shows how to create an iterator that can be used to iterate over a list of numbers:

C#

```plaintext
public IEnumerable<int> GetNumbers()
{
    int i = 0;

    while (true)
    {
        yield return i;

        i++;
    }
}
```

This code creates a method called `GetNumbers()` that returns an iterator. The `GetNumbers()` method uses the `yield` keyword to return the next number in the list. The `yield` keyword also allows the `GetNumbers()` method to continue iterating even if the list of numbers is not fully loaded into memory.

The `yield` keyword can be used to create iterators for a variety of different collections, including lists, arrays, and sets. The `yield` keyword can also be used to create iterators for custom collections.


---

Original Source: https://www.mindstick.com/forum/159057/what-is-the-use-of-the-yield-keyword-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
