When using the return type IEnumerable<T> in a .NET 7 Web API endpoint, what is the practical difference when using yield return compared to returning a populated collection?
The following code has two example endpoints to compare the scenarios:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Data;
namespace YieldTest.Controllers;
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
[HttpGet("yield-return")]
public IEnumerable<UserData> YieldReturn()
{
using var connection = new SqlConnection(connectionString);
using var command = new SqlCommand(query, connection);
connection.Open();
using var reader = command.ExecuteReader();
while (reader.Read())
yield return new(
reader.GetString("Username"),
reader.GetString("EMail")
);
}
[HttpGet("return-collection")]
public IEnumerable<UserData> ReturnCollection()
{
using var connection = new SqlConnection(connectionString);
using var command = new SqlCommand(query, connection);
connection.Open();
using var reader = command.ExecuteReader();
var users = new List<UserData>();
while (reader.Read())
users.Add(new(
reader.GetString("Username"),
reader.GetString("EMail")
));
return users;
}
const string query = "SELECT Username, EMail FROM Users";
const string connectionString = "Data Source=.;Initial Catalog=[db];User Id=[user];Password=[pwd];";
}
public record UserData(
string Username,
string Email
);