简体   繁体   中英

FluentValidation NullReferenceException - Way to prevent checking for null values?

If I have something like this:

When(x => x.SendMail.Equals("Y"), () =>
{
    RuleFor(x => x.To).NotEmpty();
    RuleFor(x => x.From).NotEmpty();
    RuleFor(x => x.EmailAddress).NotEmpty();
});

and SendMail does not have a value, I will get a NullReferenceException . However, if I surround the When() like so:

When(x => x.SendMail != null, () =>
{
    When(x => x.SendMail.Equals("Y"), () =>
    {
        RuleFor(x => x.To).NotEmpty();
        RuleFor(x => x.From).NotEmpty();
        RuleFor(x => x.EmailAddress).NotEmpty();
    });
});

it works as I would expect and I do not get a NRE when SendMail does not have a value. I'm new to FluentValidaton and C# in general. Is this the proper way to go about handling validations like this? Do I need to wrap all logic like this with null checks?

The easiest thing to do is just switch the comparison.

When(x => x.SendMail.Equals("Y"), () => // etc

becomes

When(x => "Y".Equals(x.SendMail), () => // etc

This works because "Y" is never null ( so the Equals method can be called which is where your current code fails ) and will also not throw an NRE when doing a comparison inside of the Equals method as a null value will simply return false .

I would recommend to do something like this

When(x => x.SendMail != null && x.SendMail.Equals("Y"), () =>
{
    RuleFor(x => x.To).NotEmpty();
    RuleFor(x => x.From).NotEmpty();
    RuleFor(x => x.EmailAddress).NotEmpty();
});

This way second condition of and statement ( x.SendMail.Equals("Y") ) evaluates only if first one ( x.SendMail != null ) is true. This rule it works for any boolean expression.

What you are doing can be simplified to

When(x => x.SendMail != null && x.SendMail.Equals("Y"), () =>
{
    RuleFor(x => x.To).NotEmpty();
    RuleFor(x => x.From).NotEmpty();
    RuleFor(x => x.EmailAddress).NotEmpty();
});

Or if using latest version c#

When(x => x.SendMail?.Equals("Y") ?? false, () =>
{
    RuleFor(x => x.To).NotEmpty();
    RuleFor(x => x.From).NotEmpty();
    RuleFor(x => x.EmailAddress).NotEmpty();
});

@Ryan Buening you are trying to call instance method of null object so you are getting NullReferenceException and this is normal for c#. I think you could use null conditional operator from c#6

When(x => x.SendMail?.Equals("Y"), () =>
{
    RuleFor(x => x.To).NotEmpty();
    RuleFor(x => x.From).NotEmpty();
    RuleFor(x => x.EmailAddress).NotEmpty();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM