You can create a generator-like method using yield return to
read a file line by line. This is memory-efficient, especially for large files, because it reads one line at a time and doesn’t load the whole file into memory.
Example: Generator-style file reader
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main()
{
string path = @"C:\example.txt";
foreach (var line in ReadLines(path))
{
Console.WriteLine(line);
}
}
static IEnumerable<string> ReadLines(string filePath)
{
using (var reader = new StreamReader(filePath))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
}
Why use yield return here?
Defers execution: lines are read only when needed.
Saves memory: no need to store all lines in a list or array.
Makes the code composable with LINQ or foreach.
You can combine this with LINQ filters like:
var longLines = ReadLines("file.txt").Where(l => l.Length > 80);
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You can create a generator-like method using
yield returnto read a file line by line. This is memory-efficient, especially for large files, because it reads one line at a time and doesn’t load the whole file into memory.Example: Generator-style file reader
Why use
yield returnhere?foreach.