Friday, September 19, 2025

IEnumerable vs IQueryable in C# with Examples

 When working with LINQ in C#, two commonly used interfaces are IEnumerable and IQueryable. At first glance, they may look similar, but they serve different purposes and have a big impact on performance and where the query executes (in memory vs. database).

In this article, we’ll break down the difference with real examples, pros and cons, and when to use each.


πŸ”Ή What is IEnumerable?

  • Defined in System.Collections namespace.

  • Works with in-memory collections like List, Array, Dictionary.

  • Suitable for small datasets.

  • LINQ query executes in the application memory (after loading data).

Example of IEnumerable

using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 }; // IEnumerable query (LINQ to Objects) IEnumerable<int> evenNumbers = numbers.Where(n => n % 2 == 0); Console.WriteLine("Even Numbers (IEnumerable):"); foreach (var num in evenNumbers) { Console.WriteLine(num); } } }

✅ Here, filtering (n % 2 == 0) happens inside the .NET process (in memory).


πŸ”Ή What is IQueryable?

  • Defined in System.Linq namespace.

  • Works with remote data sources (SQL Server, Cosmos DB, MongoDB, etc.).

  • Suitable for large datasets.

  • LINQ query is converted into expression trees, then executed in the database.

Example of IQueryable (Entity Framework)

using System; using System.Linq; using Microsoft.EntityFrameworkCore; public class Student { public int Id { get; set; } public string Name { get; set; } } public class MyDbContext : DbContext { public DbSet<Student> Students { get; set; } } class Program { static void Main() { using (var context = new MyDbContext()) { // IQueryable query (not executed yet) IQueryable<Student> query = context.Students .Where(s => s.Name.StartsWith("A")); Console.WriteLine("Students with names starting with A:"); foreach (var student in query) // query executes here (SQL runs) { Console.WriteLine(student.Name); } } } }

✅ Here, the filtering (s.Name.StartsWith("A")) is converted into SQL and executed in the database.


πŸ”Ή Key Differences Between IEnumerable and IQueryable

FeatureIEnumerableIQueryable
NamespaceSystem.CollectionsSystem.Linq
ExecutionIn-memory (LINQ to Objects)Remote (LINQ to SQL, Cosmos DB, etc.)
PerformanceLoads all data, then filtersFilters at DB level → efficient
Best ForSmall in-memory collectionsLarge datasets from databases
Deferred Execution✅ Yes✅ Yes
Example SourcesList, Array, DictionaryEntity Framework DbSet, ORM queries

πŸ”Ή When to Use IEnumerable vs IQueryable

  • Use IEnumerable when:

    • Working with in-memory collections (List, Array).

    • Data set is small and already loaded.

    • You need LINQ to Objects queries.

  • Use IQueryable when:

    • Fetching data from a database or remote service.

    • You want to avoid loading the entire dataset into memory.

    • Filtering/sorting should happen at the source (SQL).


πŸ”Ή Final Thoughts

Both IEnumerable and IQueryable support deferred execution, but the key difference lies in where the query is executed.

  • IEnumerable: query runs in memory → good for small collections.

  • IQueryable: query runs at the database/source → good for large datasets.

πŸ‘‰ As a best practice:

  • For Entity Framework or large data queries → use IQueryable.

  • For small in-memory operations → use IEnumerable.


✅ Now you have a clear understanding of IEnumerable vs IQueryable with real-world .NET examples.

Singleton vs Static in .NET: Key Differences Explained

 When working with .NET applications, one of the most common confusions developers face is the difference between Singleton and Static. Both provide global access, but they are not the same thing. In this article, we will dive deep into the definition, usage, and differences between Singleton and Static in .NET with real-world examples.


✅ What is Singleton in .NET?

A Singleton is a design pattern that ensures only one instance of a class is created throughout the application’s lifetime. It provides a global point of access while still following object-oriented principles like inheritance, interfaces, and polymorphism.

Example: Logger Singleton

public sealed class Logger { private static readonly Lazy<Logger> instance = new Lazy<Logger>(() => new Logger()); private Logger() { } // private constructor public static Logger Instance => instance.Value; public void Log(string message) { Console.WriteLine($"Log: {message}"); } }

Usage:

Logger.Instance.Log("Application started");

πŸ‘‰ Real-world use cases of Singleton:


✅ What is Static in .NET?

A Static class in .NET is a special class that cannot be instantiated. All its members (methods, variables, properties) are static and directly accessible via the class name.

Example: Static Helper Class

public static class MathHelper { public static int Square(int number) => number * number; }

Usage:

int result = MathHelper.Square(5); // 25

πŸ‘‰ Real-world use cases of Static:


πŸ”‘ Key Differences Between Singleton and Static in .NET

FeatureSingletonStatic
DefinitionDesign patternLanguage keyword
Object creationOne instance createdNo instantiation
Memory lifetimeManaged by Garbage CollectorLives entire application domain
Supports OOP (Inheritance, Interfaces, Polymorphism)✅ Yes❌ No
Thread safetyNeeds handling (lock, Lazy<T>)CLR ensures thread-safe initialization
State managementMaintains instance stateGlobal state only
Best use caseServices, configurations, DB connectionsUtilities, constants, helper methods

🧠 When to Use Singleton vs Static in .NET

  • Use Singleton when:

    • You need a single object with state.

    • You want to implement OOP features like interfaces or inheritance.

    • Example: Logging service, configuration manager, database connection.

  • Use Static when:

    • You need stateless utility functions.

    • You want a class with only constants or helper methods.

    • Example: Math functions, string helpers, conversion utilities.


πŸ“Œ Final Thoughts

Both Singleton and Static provide global access in .NET, but they solve different problems.

Choosing the right one depends on whether your requirement involves state + OOP (go for Singleton) or just global utility (go for Static).

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages