Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an ArgumentNullException on a property [duplicate]

Tags:

c#

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?

like image 849
Luke101 Avatar asked Sep 06 '25 07:09

Luke101


2 Answers

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");
}
like image 57
Jon Skeet Avatar answered Sep 10 '25 08:09

Jon Skeet


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.

like image 44
David Avatar answered Sep 10 '25 08:09

David