Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of ArgumentNullException when accessing arguments' properties

Suppose I have a class Foo with a complex property Bar. Then, suppose I have a method like the following in some other class:

public void DoSomething(Foo foo)
{
    if (foo == null)
        throw new ArgumentNullException("foo");
    if (foo.Bar == null)
        throw new ArgumentNullException("bar");
}

Is the use of an ArgumentNullException appropriate here even though, strictly speaking, foo.Bar is not an argument in this case? I have read and can appreciate that it is not appropriate to throw a NullReferenceException manually. Is this telling me that I need to abstract?

public void DoSomething(Foo foo)
{
    if (foo == null)
        throw new ArgumentNullException("foo");
    DoSomethingElse(foo.Bar);
}

private void DoSomethingElse(Bar bar)
{
    if (bar == null)
        throw new ArgumentNullException("bar");
}

Is my first code snippet the "correct" usage of ArgumentNullException? What is the conventional way of handling this situation?

Thanks.

like image 388
Ant P Avatar asked Feb 26 '13 21:02

Ant P


1 Answers

Ideally, the Foo class would ensure that its Bar property is never null. If that's not possible, I would throw an ArgumentException in this case since the argument is not null, but it is invalid.

like image 97
Lee Avatar answered Sep 19 '22 05:09

Lee