What is “yield return” in C# ? How to use?

You might have heard about a keyword called “yield“, It is a contextual keyword in .NET and it makes the method’s context an iterator, which means your method can serve the purpose of an iterator by using yield return.

Using the same code as in loading data in DataGrid Asynchronously, we can simply make the GetCustomers() method an iterator and just use the foreach loop to iterate and load customers in the Datagrid.

You might have the ViewModel like this:

public class ShellViewModel
{
  private ObservableCollection<Customer> _customers;
  
  public ObservableCollection<Customer> Customers
  {
    get { return _customers; }
    set { _customers = value; }
  }
  public ShellViewModel()
  {
    _customers = new ObservableCollection<Customer>();
  }

  public void LoadData()
  {
    //GetCustomers reading from database and returns one by one
    foreach (Customer c in DataHelper.GetCustomers())
    {
      _customers.Add(c);
    }    
  }
}

Here in LoadData() method, we are using the foreach method to get the customers but previously GetCustomers() method needs to complete execution and returns all the Customers, and then it iterates on the customers.

Here’s how you can make the GetCustomers() method an iterator itself and returns a customer instance one by one instead of the complete list.

public static IEnumerable<Customer> GetCustomers()
{
  using (SqlConnection connection = new SqlConnection(Configurations.ConnectioString))
  {
    SqlCommand selectCmd = new SqlCommand("SELECT * FROM dbo.Customers", connection);
    connection.Open();
    IDataReader reader = selectCmd.ExecuteReader(CommandBehavior.CloseConnection);
    
    while (reader.Read())
    {
      yield return new Customer()
      {
        CustomerId = reader.GetInt32(0),
        FirstName = reader.GetString(1),
        LastName = reader.GetString(2),
        Address = reader.GetString(3),
        CreatedTime = reader.GetDateTime(4),
        UpdatedTime = reader.GetDateTime(5)
      };
    }
  }
}

yield keyword makes the context of the GetCustomers() method as an iterator.

In simple terms, yield makes the method return the customer instances one by one and can be utilized while another customer instance is in making.

Read more about yield here.