I have a method where it checks if a property is null or not. I know how to throw an arguement null exception if the object is null but how do you throw an arguementnullexception for a property on the object.
private int CalculateCompletedDateDiff(Recall recall)
{
if (!recall.StartDate.HasValue)
{
throw new ArgumentNullException("recall.StartDate");
}
//calculate and return
}
I am using resharper and there is purple scriggly under recall.StartDate
that says cannot resolve symbol. So, if the StartDate cannot be null what is the correct way to throw an arguementnull exception on the startdate property?
You shouldn't throw ArgumentNullException
if the argument (recall
) isn't null. Just ArgumentException
is appropriate here when it's some problem with the argument other than it being null:
if (recall == null)
{
throw new ArgumentNullException("recall");
}
if (recall.StartDate == null)
{
throw new ArgumentException("StartDate of recall must not be null",
"recall");
}
ReSharper is probably suggesting that you do a null reference check on recall
before de-referencing it? Maybe something like this:
if (recall == null)
throw new ArgumentNullException("recall");
if (!recall.StartDate.HasValue)
throw new ArgumentNullException("recall.StartDate");
Semantically I'm not sure if this is really the proper use of an ArgumentNullException
, though. Since StartDate
isn't an argument to the method. This may be personal opinion, but I'd recommend putting the logic for the validity of StartDate
into the Recall
object itself. Of course, the logic to define that isn't known from the question, so it's really just thinking out loud at this point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With