skip to Main Content

Consider the following C# Code Fragment:

public class Person
{
    public int Id { get; set;}
    public string? Name { get; set;}
    public string? Description {get; set;}
}


List<Person>? _persons = new List<Person>();

// Something populates the _persons list;

//Use LINQ like this.
Person? person = _persons. Where (person=>person.Name == "someName").FirstOrDefault();

In the LINQ a CS8602 warning is raised because person.Name has the possibility of being null. Based on the Person Class this is definitely possible and expected. However, in that case the null is not equal to "someName" so I would not expect records that have their name property set to null to not be returned anyway.

Is there a syntax that will permit the query without having this warning? I am using .Net 8 and Visual Studio 2022.

Thanks

2

Answers


  1. Personally, I always avoid using nulls when working with LINQ. Your code might change in the future, depending on the size so it becomes more robust.

    Person? person = _persons.Where(person => person.Name != null && person.Name == "someName").FirstOrDefault();
    

    However, if you still want to ignore the null warning, you can use the null-forgiving operator "!"

    Person? person = _persons.Where(person => person.Name! == "someName").FirstOrDefault();
    
    Login or Signup to reply.
  2. You could use Equals(), like

    person=>"someName".Equals(person.Name)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search