Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top