Lỗi call to a member function nullable on null năm 2024

When you have a statement like A.B.C = E.F;, and you receive an NullReferenceException 'Object reference not set to an instance of an object.' on that line of code, it basically means either A, or B or E are null.

To figure out what's wrong there, you can set a breakpoint on the same line, start debugging and then when the breakpoint hits, just check the value of A, B or E.

When NullReferenceException happens?

There are some common cases that you may encounter a NullReferenceException. Here is a summary based on NllReferenceEexception article in .NET documentations. I've put the link of the article in the next section in the answer, where you can find some useful example as well.

A NullReferenceException exception is thrown when you try to access a member on a type whose value is null. A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios:

A

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

1 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,

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

1 is not generally raised by the

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

3 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

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

4comes under the class of

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

5, which is inherited from the

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

6 class. The

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

6 class is in turn inherited from the

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

8 class, which is inherited from the

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

9 class.

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

When does the ArgumentNullException occur in C#?

Generally, there are two major circumstances when an

class Program
    {
        static void Main[string[] args]
        {
            string id = null;
            int ans = int.Parse[id]; // error is thrown
        }
    }

0 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

class Program
    {
        static void Main[string[] args]
        {
            string id = null;
            int ans = int.Parse[id]; // error is thrown
        }
    }

1 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

class Program
    {
        static void Main[string[] args]
        {
            string id = null;
            int ans = int.Parse[id]; // error is thrown
        }
    }

2, two private strings,

class Program
    {
        static void Main[string[] args]
        {
            string id = null;
            int ans = int.Parse[id]; // error is thrown
        }
    }

3 and

class Program
    {
        static void Main[string[] args]
        {
            string id = null;
            int ans = int.Parse[id]; // error is thrown
        }
    }

4, and used them for the public properties of

class Program
    {
        static void Main[string[] args]
        {
            string id = null;
            int ans = int.Parse[id]; // error is thrown
        }
    }

5and

class Program
    {
        static void Main[string[] args]
        {
            string id = null;
            int ans = int.Parse[id]; // error is thrown
        }
    }

6respectively. Then we wrote custom

class Program
    {
        static void Main[string[] args]
        {
            string id = null;
            int ans = int.Parse[id]; // error is thrown
        }
    }

7 and

class Program
    {
        static void Main[string[] args]
        {
            string id = null;
            int ans = int.Parse[id]; // error is thrown
        }
    }

8 functions that checked whether or not the passed argument value was null.

If true, we throw in a new

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

1 instead of passing the entire message, as is frequently the case,

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

1 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

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

1 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

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

2 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,

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

1 occurs as the argument of

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

4cannot 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

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

2 block in this case because the value is being checked in the

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

6method.

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:

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

0

Avoiding ArgumentNullExceptions

To summarize, an

class Program
    {
        static void Main[string[] args]
        {
            string id = null;
            int ans = int.Parse[id]; // error is thrown
        }
    }

0 comes from

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

8 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

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

9, it’s always good practice to perform a

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];
        }
    }
}

0 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!

Chủ Đề