ArgumentNullException for nested elements

Let's say I have a method:

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

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

Clearly, I should use ArgumentNullException as shown above to verify that the user is not null. Now, how can I verify that user.Name is not empty? It would be good practice to do this:

if (string.IsNullOrWhiteSpace(user.Name))
    throw new ArgumentNullException("user", "Username is empty");
+4
source share
2 answers

No, you should not throw an ArgumentNullException for this purpose, as it is specifically designed to access links null.

, null (Nothing in Visual Basic) , .

ArgumentException . InvalidUserException - .

msdn .

ArgumentNullException ArgumentException. , , , . , ,

, , null ArgumentNullException ArgumentException .

, - User . User , Name null.

+8

ArgumentException, , ArgumentNullException :

if (string.IsNullOrWhiteSpace(user.Name))
    throw new ArgumentException("Username is empty", "user");
+3

Source: https://habr.com/ru/post/1569300/


All Articles