CodexBloom - Programming Q&A Platform

C# - Handling Nullable Reference Types in LINQ with Unexpected NullReferenceException

👀 Views: 23 💬 Answers: 1 📅 Created: 2025-06-20
c# linq nullable-types nullreferenceexception C#

I'm learning this framework and Does anyone know how to After trying multiple solutions online, I still can't figure this out. I've been banging my head against this for hours. I'm working on a .NET 6 application that makes extensive use of LINQ to filter a list of custom objects. I've enabled nullable reference types in my project, but I'm working with a `NullReferenceException` when trying to filter this list. My custom class looks like this: ```csharp public class Person { public string Name { get; set; } public int? Age { get; set; } } ``` I have a list of `Person` objects: ```csharp var people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = null }, new Person { Name = "Charlie", Age = 25 } }; ``` The goal is to get all people who have an age greater than 20. I wrote the following LINQ query: ```csharp var filteredPeople = people.Where(p => p.Age > 20).ToList(); ``` However, I'm working with this exception at runtime: ``` NullReferenceException: Object reference not set to an instance of an object. ``` I assumed that the `null` value for `Age` would be handled gracefully, but it seems like the LINQ query is still attempting to evaluate the condition for `null` ages. To debug, I added a check like this: ```csharp var filteredPeople = people.Where(p => p.Age.HasValue && p.Age > 20).ToList(); ``` This resolved the scenario, but I would like to know if this is the best approach when working with nullable types in LINQ. Is there a more elegant way to handle nullable types in such queries without running into `NullReferenceException`? Also, are there any best practices I should follow when using nullable reference types in LINQ? I’ve seen conflicting opinions online and would appreciate any insights on this topic. For context: I'm using C# on Linux. What am I doing wrong? I'm working on a web app that needs to handle this. Cheers for any assistance! I'm open to any suggestions.