CodexBloom - Programming Q&A Platform

Inconsistent behavior of NullReferenceException during LINQ operations in C# 10

👀 Views: 1289 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-26
LINQ NullReferenceException C# 10 C#

I've hit a wall trying to I'm experiencing an scenario where a `NullReferenceException` is being thrown intermittently when using LINQ queries on a list of custom objects. This happens specifically when I'm trying to filter a list based on a property that can sometimes be null. Here's a simplified version of my code: ```csharp public class Product { public string Name { get; set; } public string Description { get; set; } } List<Product> products = new List<Product> { new Product { Name = "Product1", Description = null }, new Product { Name = "Product2", Description = "A useful product" }, new Product { Name = "Product3", Description = null } }; var filteredProducts = products.Where(p => p.Description.Contains("useful")); ``` I expect this to skip products without a description, but I'm getting a `NullReferenceException` on the line where I'm trying to filter. I tried adding a null check like this: ```csharp var filteredProducts = products.Where(p => p.Description != null && p.Description.Contains("useful")); ``` However, it still throws an exception, and I need to figure out why. I'm using .NET 6.0, and the scenario seems to occur during runtime, but I need to reproduce it consistently. Is there something specific about how LINQ handles null values that I might be missing, or is there a better way to handle this situation? Any insights would be greatly appreciated! The stack includes C# and several other technologies. Thanks in advance!