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.
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.
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