TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# NullReferenceException and Null Parameter

This C# exception article demonstrates NullReferenceException.

NullReferenceException is common.

It indicates that you are trying to access member fields, or function types, on an object reference that points to null. It indicates a flaw in the code.

Null

Example. First, it is useful to look at an example of a short program that causes this exception to be raised. The program explicitly assigns the string reference variable to the null literal.

Note: This means that the string variable does not point to any object on the managed heap. It is equivalent to a null pointer.

C# program that raises NullReferenceException

using System;

class Program
{
    static void Main()
    {
	string value = null;
	if (value.Length == 0) // <-- Causes exception
	{
	    Console.WriteLine(value); // <-- Never reached
	}
    }
}

Output

Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at Program.Main() in C:\Users\...

The program defines the Main entry point. The string reference variable is assigned to the null literal. Next, the Length property is accessed on the string reference. The program compiles correctly, but will always throw an execution.

Note: You cannot access an instance property like Length on a null reference. An exception will always occur.

Example 2. We see one way you can prevent the null reference exception from being thrown. Often in programs, methods receive reference value parameters. The parameters contain the storage location of an object on the managed heap.

However: If the parameter points to null, the compiler will not know this at compile-time. You must check for null at the method start.

C# program that checks for null in method

using System;

class Program
{
    static void Main()
    {
	// Create an array and use it in a method.
	int[] array = new int[2];
	array[0] = 1;
	array[1] = 2;
	Test(array);

	// Use null reference in a method.
	array = null;
	Test(array); // <-- Won't crash
    }

    static void Test(int[] array)
    {
	if (array == null)
	{
	    // You can throw an exception here, or deal with the argument.
	    return;
	}
	int rank = array.Rank;
	Console.WriteLine(rank);
    }
}

The Main entry point is where control flow begins in the example. An array containing two elements is passed to the Test method. The Test method internally checks the reference value parameter against the null literal.

Therefore: It will not throw when passed a null reference, as we see in the latter part of the Main method.

Discussion. Exception handling is a complex topic. And developers have different strategies. However, the common theme to the best approaches is to always log the exceptions and work to prevent them from happening in normal runtime operation.

Also: In many programs you can use ArgumentNullException to notify the caller of errors.

Handling null references. If you have total control over the callers of a method and it can never be called with a null parameter, it is preferable not to check the parameter for null.

But: For libraries and code APIs that will be used by others, more careful parameter checking to avoid NullReferenceExceptions is best.

Opcodes. Microsoft lists the opcodes that cause the NullReferenceException to be thrown in some conditions. Usually it is easiest to step through your code in Visual Studio, but opcodes also provide insight into the functionality of your code.

NullReferenceException: MSDN

Summary. We looked the NullReferenceException error reporting class in the System namespace, using the C# language. You will encounter this exception when you attempt to access a member on a null variable.

And: This will only occur on instances that are reference types. You will need to deal with null parameters in certain cases.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf