I am sure most of you are already aware of this, but thought of clarifying the things, if someone is looking for it.
Basically ArgumentException is deriving from SystemException where as ArgumentNullException is deriving from ArgumentException. So while ArgumentException is more generic, ArgumentNullException is more specific.
Let's consider the following scenario. I have an Employee class and it has three properties.
public class Employee { public string FirstName { get; } public string LastName { get; } public string JobRole { get; set; } public Employee(string firstName, string lastName) { FirstName = firstName ?? throw new ArgumentNullException(nameof(firstName)); LastName = lastName ?? throw new ArgumentNullException(nameof(lastName)); } }
Employee should have FirstName, LastName, but JobRole is optional when you are creating an employee.
In here as you can see, in the constructor we must be using ArgumentNullException instead of ArgumentException, because we are checking argument itself is null.
Consider the below method. It’s accepting an employee and let’s say we are going to do something with the employee’s JobRole, and to do that employee's JobRole should have set first.
public void SomeMethod(Employee employee) { if (employee == null) throw new ArgumentNullException(nameof(employee)); if (employee.JobRole == null) throw new ArgumentException($"{nameof(employee)}.{nameof(JobRole)} cannot be null");
// TODO: Implementation }
So here, first we have checked whether the employee is null, if yes, we are throwing an ArgumentNullException. Then we need to check whether the employee’s JobRole is set or not. So if the JobRole of employee is null, we are throwing ArgumentException, but not an ArgumentNullException. The reason is even though the property is null, it has made the employee argument itself to invalid.
Well, hope you understood the difference. Even though these are simple things, these things matters when it comes to writing quality code.
Happy Coding.
Regards,
Jaliya
Jaliya
No comments:
Post a Comment