Reputation: 1660
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?
Upvotes: 2
Views: 3396
Reputation: 62213
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
.
Upvotes: 4
Reputation: 29
@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();
});
Upvotes: 0
Reputation: 247133
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();
});
Upvotes: 2
Reputation: 1538
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.
Upvotes: 3