Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArgumentNullException for nested members [closed]

Let's say I have a method:

public void SayHello(User user)
{
    if (user == null)
        throw new ArgumentNullException(nameof(user));

    Console.Write(string.Format("Hello from {0}", user.Name));
}

It's clear that I should use ArgumentNullException as it shown above to validate that user is not null. Now how can I validate that user.Name is not empty? Would it be a good practice to do like that:

if (string.IsNullOrWhiteSpace(user.Name))
    throw new ArgumentNullException("user", "Username is empty");
like image 550
Andrei Avatar asked Dec 29 '14 13:12

Andrei


2 Answers

No you shouldn't throw ArgumentNullException for this purpose as it is designed specifically to address null references.

The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.

Instead you should be using ArgumentException or your own subclass of it. let's say InvalidUserException or something similar.

Even msdn talks about.

ArgumentNullException behaves identically to ArgumentException. It is provided so that application code can differentiate between exceptions caused by null arguments and exceptions caused by arguments that are not null. For errors caused by arguments that are not null

So it is clear that if argument is null use ArgumentNullException and ArgumentException otherwise.

That said, Ideally you shouldn't even allow someone to create an instance of User with invalid username. I'd really design my User class in such a way that it can never contain Name as null.

like image 128
Sriram Sakthivel Avatar answered Oct 16 '22 22:10

Sriram Sakthivel


You should throw ArgumentException if the argument is empty, ArgumentNullException should only be used for null arguments:

if (string.IsNullOrWhiteSpace(user.Name))
    throw new ArgumentException("Username is empty", "user");
like image 5
Lee Avatar answered Oct 16 '22 21:10

Lee