Blog |

How to Handle the Argument Null Exception in C#

How to Handle the Argument Null Exception in C#
Table of Contents

A System.ArgumentNullException occurs when an invalid argument is passed to a method in C#. In this case, it refers to the passing of a null object when the method expects a non-null object or a value. Similar to other exceptions raised as a result of arguments, System.ArgumentNullException is not generally raised by the .NET framework itself or the Common Language Runtime (CLR). Instead, it is thrown by an application or a library as an indication of improper null arguments.

 

Syntax of ArgumentNullException

Similar to any class or method, exceptions also have their own syntax.

Below is the syntax for ArgumentNullException:

public class ArgumentNullException : ArgumentException

The ArgumentNullException comes under the class of ArgumentException, which is inherited from the SystemException class. The SystemException class is in turn inherited from the Exception class, which is inherited from the Object class.

Object -> Exception -> SystemException -> IOException -> FileNotFoundException

 

When does the ArgumentNullException occur in C#?

Generally, there are two major circumstances when an ArgumentNullException is thrown, both of which reflect developer errors:

  • An object returned from a method call is then passed as an argument to a second method, but the value of the original returned object is null. To prevent the error, check for a return value that is null and call the second method only if the return value is not null.
  • An uninstantiated object is passed to a method. To prevent the error, instantiate the object.

 

Example One: Working with an Inbuilt Function like Parse()

In the below code, we are trying to parse and convert a string value to an integer value, assuming that the string is valid and contains only numbers.

class Program
    {
        static void Main(string[] args)
        {

            string id = null;
            int ans = int.Parse(id); // error is thrown

        }
    }

 

Output of Example 1

We can see that StringToNumber is causing the error because its parameter should not be null.

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: String
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Int32.Parse(String s)
   at ConsoleApp1.Program.Main(String[] args) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 50

 

Example Two: Dealing with Custom Classes

In the below code we have created a class Books, two private strings, author and title, and used them for the public properties of Author and Title respectively. Then we wrote custom Title.set () and Author.set () functions that checked whether or not the passed argument value was null.

If true, we throw in a new System.ArgumentNullException instead of passing the entire message, as is frequently the case, System.ArgumentNullException expects just the name of the argument, which should not be null.

namespace ConsoleApp1
{

    public class Books
    {
        private string authors;
        private string titles;
        public string Author
        {
            get { return authors; }
            set {

                if (value is null)

                    throw new System.ArgumentNullException("Author");

                authors = value; 
                }
        }

        public string Title
        {
            get { return titles; }
            set {
                if (value is null)

                    throw new System.ArgumentNullException("Title");
                titles = value; }

        }

        public Books(string title, string author)
        {
            Author = author;
            Title = title;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            var obj = new Books("Harry potter", null);

        }
    }
}

 

Output of Example Two

When the above code is run we get the following output:

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: Author
   at ConsoleApp1.Books.set_Author(String value) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 21
   at ConsoleApp1.Books..ctor(String title, String author) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 39
   at ConsoleApp1.Program.Main(String[] args) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 49

The parameter Author is causing this exception as its value should not be null.

 

How to Handle ArgumentNullException in C#

Now let’s see how to debug and handle this exception in C#. The best approach is to use try-catch block and perform a simple check before passing the values. Let’s see how to fix both examples discussed earlier.

 

How to Fix Example One:

On observing the first few lines of the output from the bottom to the top, it is quite evident that when parsing a string to convert the string to a number, System.ArgumentNullException occurs as the argument of int.Parse()cannot be null.

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: String
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)

 

Working Code:

class Program
    {
        static void Main(string[] args)
        {

            try
            {
                string id = null;

                if (id is null)
                {
                    throw new ArgumentNullException("Id Argument cannot be null");
                }
                else {
                    int ans = int.Parse(id);
                }

            }catch (ArgumentNullException e)
            {
                Console.WriteLine(e.Message);
            }

        }
    }

 

Output:

Value cannot be null.
Parameter name: Id Argument cannot be null

 

How to Fix Example Two:

Implement a try-catch block in this case because the value is being checked in the set() method.

 

Working Code:

namespace ConsoleApp1
{

    public class Books
    {
        private string authors;
        private string titles;
        public string Author
        {
            get { return authors; }
            set {

                if (value is null)

                    throw new System.ArgumentNullException("Author");

                authors = value; }
        }

        public string Title
        {
            get { return titles; }
            set {
                if (value is null)

                    throw new System.ArgumentNullException("Title");
                titles = value; }

        }

        public Books(string title, string author)
        {
            Author = author;
            Title = title;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            try
            {

                var obj = new Books("Harry potter", null);
            }catch(ArgumentNullException e)
            {
                Console.WriteLine(e.Message);
            }

        }
    }
}

 

Output:

Value cannot be null.
Parameter name: Author

 

Avoiding ArgumentNullExceptions

To summarize, an ArgumentNullException comes from ArgumentExceptions when an invalid argument is passed to a method. In this case, it refers to passing a null object when the method expects a non-null object or a value. Furthermore, whenever dealing with strings, it’s always good practice to perform a null check and then pass any arguments.

 

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing C# errors easier than ever. Sign Up Today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape