DarthVader
DarthVader

Reputation: 55032

Null object in Func

I have a filter as below:

filter = project => project.Plan.ProgressStatus == progressStatus;

I am creating a filter based on progressStatus that is passed into method.

Then I pass this filter to a where operator.

var projects = _projectService.Where(filter);

I get back NRE since Plan is null.

How can I safely query objects whose Plan.ProgressStatus is equal to what i pass in as parameter?

Upvotes: 0

Views: 63

Answers (2)

clcto
clcto

Reputation: 9648

Make your filter check if it is null:

filter = project => project.Plan != null && project.Plan.ProgressStatus == progressStatus;

If _projectService possibly contains null then add that check as well:

filter = project => project != null
                 && project.Plan != null 
                 && project.Plan.ProgressStatus == progressStatus;

Upvotes: 3

DLeh
DLeh

Reputation: 24395

Add a null check to the project and/or project.Plan objects in your func.

filter = project => 
{
    if(project == null || project.Plan == null)
        return false;
    return project.Plan.ProgressStatus == progressStatus;
};

Upvotes: 0

Related Questions