0
0
C Sharp (C#)programming~5 mins

Deferred execution behavior in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Deferred execution means the code to get data runs only when you actually need the data. This helps save time and memory.

When you want to delay getting data until you really need it.
When working with large collections and want to avoid unnecessary work.
When chaining multiple queries and want them to run as one combined query.
When you want to improve performance by not loading all data at once.
When you want to build flexible queries that run later.
Syntax
C Sharp (C#)
var result = collection.Where(x => x > 5);

The query does not run immediately.

The data is fetched only when you use result, like in a foreach loop.

Examples
This creates a query to get numbers greater than 3, but does not run it yet.
C Sharp (C#)
var numbers = new List<int> {1, 2, 3, 4, 5};
var filtered = numbers.Where(n => n > 3);
The query runs here, printing numbers greater than 3.
C Sharp (C#)
foreach(var num in filtered) {
    Console.WriteLine(num);
}
The query runs here to count how many numbers are greater than 3.
C Sharp (C#)
var count = filtered.Count();
Sample Program

This program shows that the filtering code runs only when we start looping over the results, not when we create the query.

C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
    static void Main() {
        var numbers = new List<int> {1, 2, 3, 4, 5};
        var filtered = numbers.Where(n => {
            Console.WriteLine($"Checking {n}");
            return n > 3;
        });

        Console.WriteLine("Query created, but not run yet.");

        Console.WriteLine("Iterating results:");
        foreach(var num in filtered) {
            Console.WriteLine(num);
        }
    }
}
OutputSuccess
Important Notes

Deferred execution helps improve performance by delaying work.

Be careful: if the source collection changes before you run the query, results may change.

To force immediate execution, use methods like ToList() or ToArray().

Summary

Deferred execution means queries run only when needed.

This saves time and memory by avoiding unnecessary work.

Use foreach or methods like Count() to trigger execution.