Skip to content

NullReferenceException when property is null #2152

@MeikelLP

Description

@MeikelLP

FluentValidation version

latest

ASP.NET version

No response

Summary

When you validate an object that may have nullable properties:

public class NullType {
	public List<int> List { get; set; }
}

and you validate their property without checking for null first

public class NullReferenceValidator : AbstractValidator<NullType> {
	public NullReferenceValidator() {
		RuleFor(x => x.List.Count).NotEmpty();
	}
}

It throws a generic NullReferenceException because the rule (Expression / Func) cannot be compiled. From what I read so far this is by design. However this is very hard to debug and to find out what property exactly is failing. I forked this repo and modified the Create in PropertyRule to include the expression in the closure. When you run you app in debug mode this massively helps you find out what property is null.

However this obviously has some downsides to:

  • Performance due to increased allocations (I don't really know how to fix this here)
  • Readability (may be improved somehow)

See repo for details. I even added a test to showcase this behaviour.

Is this the only way to debug this behaviour or is there another way?

Steps to Reproduce

See repo:
main...MeikelLP:FluentValidation:fix-null-debuggability

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions