3

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Luke101
  • 63,072
  • 85
  • 231
  • 359
  • 1
    It will be indicating that recall could be null - that's why and to do a check on the object for null before evaluating. – Ahmed ilyas Jan 02 '15 at 14:56

2 Answers2

17

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");
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

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.

David
  • 208,112
  • 36
  • 198
  • 279