System nullreferenceexception как исправить

TOC Time for another post in the series Debugging common .NET exceptions. Today's exception is, without a doubt, the error most people have experienced: System.NullReferenceException. The exception happens when you try to invoke a reference that you were expecting to point to an object but in fact, points to null. Let's get started! Handling the error There are some clever ways to avoid a NullReferenceException, but before we start looking into those, let us see how the exception can b

Debugging System.NullReferenceException — Object reference not set to an instance of an object

TOC

Time for another post in the series Debugging common .NET exceptions. Today’s exception is, without a doubt, the error most people have experienced: System.NullReferenceException. The exception happens when you try to invoke a reference that you were expecting to point to an object but in fact, points to null. Let’s get started!

Debugging System.NullReferenceException - Object reference not set to an instance of an object

Handling the error

There are some clever ways to avoid a NullReferenceException, but before we start looking into those, let us see how the exception can be caught. Being a plain old C# exception, NullReferenceException can be caught using a try/catch:

try
{
    string s = null;
    s.ToString();
}
catch (NullReferenceException e)
{
    // Do something with e, please.
}

Running the code above will produce the following error:

System.NullReferenceException: Object reference not set to an instance of an object.

Debugging the error

We already know why the exception is happening. Something is null. When looking at the code above, it’s clear that s is null and the stack trace even tells us that:

stacktrace_1571989670

Sometimes spotting what is null can be hard. Take a look at the following example:

var street = service.GetUser().Address.Street;

If the code above throws a NullReferenceException, what is null? service? The result of GetUser()? Address? At first glance, Visual Studio isn’t exactly helpful either:

NullReferenceException in Visual Studio

There is a range of different ways to find out what is going on. Let’s look at the most commonly used ones.

Splitting chained method-calls to multiple lines

Spotting which call that caused an error is a lot easier if the calls are split into multiple lines:

var service = new Service();
var user = service.GetUser();
var address = user.Address;
var street = address.Street;

Running the code reveals the actual call causing the exception:

NullReferenceException in Visual Studio 2

In the example above user.Address returns null, why address.Street causes the NullReferenceException.

While splitting code into atoms like this can help debug what is going wrong, it’s not preferable in terms of readability (IMO).

Using Null Reference Analysis in Visual Studio

If you are on Visual Studio 2017 or newer (if not, now is the time to upgrade), you will have the Null Reference Analysis feature available. With this in place, Visual Studio can show you exactly what is null. Let’s change the example back to method-chaining:

var street = service.GetUser().Address.Street;

To enable the analysis go to Debug | Windows | Exception Settings. Check Common Language Runtime Exceptions (if not already checked) or extend the node and check the exceptions you are interested in. In this case, you can check System.NullReferenceException. When running the code, the debugger breaks on the NullReferenceException and you now see the Exception Thrown window:

Exception Thrown Window

Voila! The window says «ConsoleApp18.User.Address.get returned null». Exactly what we wanted to see. This will require you to run the code locally, though. If you are experiencing the exception on your production website, the Null Reference Analysis will not be available, since this is a feature belonging to Visual Studio (unfortunately). With that said, you can attach a debugger to a remote site running on Azure as explained here: Introduction to Remote Debugging on Azure Web Sites.

Fixing the error

There are various ways to fix NullReferenceException. We’ll start with the simple (but dirty) approach.

Using null checks

If null is an allowed value of an object, you will need to check for it. The most simple solution is to include a bunch of if-statements.

if (service != null)
{
    var user = service.GetUser();
    if (user != null)
    {
        var address = user.Address;
        if (address != null)
        {
            var street = address.Street;
        }
    }
}

The previous code will only reach address.Street if everything else is not null. We can probably agree that the code isn’t exactly pretty. Having multiple nested steps is harder to read. We can reverse the if-statements:

if (service == null) return;
var user = service.GetUser();
if (user == null) return;
var address = user.Address;
if (address == null) return;
var street = address.Street;

Simpler, but still a lot of code to get a street name.

Using null-conditional operator

C# 6 introduced a piece of syntactic sugar to check for null: null-conditional operator. Let’s change the method-chain example from before to use the «new» operator:

var user = service?.GetUser()?.Address?.Street;

The ? to the right of each variable, corresponds the nested if-statements from previously. But with much less code.

Use Debug.Assert during development

When getting a NullReferenceException it can be hard to spot the intent with the code from the original developer. Rather than including if-statements, it can be clearer for future authors of your code to use the Debug.Assert-method. Much like in a xUnit or NUnit test, you use Assert to verify the desired state on your objects. In the example from above, the service object could have come through a parameter or a constructor injected dependency:

class MyClass
{
    Service service;
    
    public MyClass(Service service)
    {
        this.service = service;
    }
    
    public string UserStreet()
    {
        return service.GetUser().Address.Street;
    }
}

To make a statement in your code that service should never be allowed to have the value of null, extend the constructor:

public MyClass(Service service)
{
    Debug.Assert(service != null);
    this.service = service;
}

In the case MyClass is constructed with null, the following error is shown when running locally:

Assert error

Use nullable reference types in C# 8.0

When designing code you often end up expecting parameters to be not null but end up checking for null to avoid a NullReferenceException. As you already know, all reference types in C# can take the value of null. Value types like int and boolean cannot take a value of null unless explicitely specified using the nullable value type (int? or Nullable<int>). Maybe it should have been the other way around with reference types all along?

C# 8 can fix this with nullable reference types (maybe NOT nullable reference types is a better name). Since this is a breaking change, it is launched as an opt-in feature. Nullable reference types are a great way to avoid NullReferenceExceptions, since you are very explicit about where you expect null and where not.

To enable not nullable reference types, create a new .NET Core 3 project and add the following to the csproj file:

<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>

You should be on C# 8 already, but to make it explicit, I’ve added the LangVersion element. The Nullable element enables nullable reference types. Out of the box, C# 8 creates a warning if it identifies the use of null where a value is expected. Let’s see how that looks:

class Program
{
    static void Main()
    {
        new Program().SayHello(null);
    }

    public void SayHello(string msg)
    {
        Console.WriteLine(msg);
    }
}

When compiling we see the following warning:

Program.cs(9,36): warning CS8625: Cannot convert null literal to non-nullable reference type. [C:projectscore3core3.csproj]

I know you are not one of them, but some people developed a warning-resistance which means that warnings are simply ignored. To overcome this, make sure that errors like this causes build errors over warnings by adding the following to csproj:

<WarningsAsErrors>CS8602,CS8603,CS8618,CS8625</WarningsAsErrors>

This will tell the C# compiler to treat these four nullable reference type warnings as errors instead.

Just to make it clear, allowing null in the msg parameter, you use the ? characters as with value types:

public void SayHello(string? msg)
{
    ...
}

Logging and monitoring

Logging and monitoring for null reference exceptions are a must. While some developers tempt to create control flow from exceptions (no-one should), null reference exceptions should never happen. This means that a System.NullReferenceException is a type of exception that should always be logged and fixed. A null check through either an if statement or the null-conditional operator is always the preferred way of handling potential null values. But make sure to implement a logging strategy that logs all uncaught exceptions, including the System.NullReferenceException.

When logging a System.NullReferenceException in a log file, database, elmah.io, or similar, it can be hard to spot what is null. You typically only see the method-name that causes the NullReferenceException and the Null Reference Analysis feature is only available while debugging inside Visual Studio. I will recommend you to always Include filename and line number in stack traces. This will pinpoint the exact line where the error happens.

elmah.io: Error logging and Uptime Monitoring for your web apps

This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.

elmah.io app banner

See how we can help you monitor your website for crashes
Monitor your website

C# NullReferenceException

Introduction of C# NullReferenceException

The NullReferenceException is an exception that is thrown by the program when we attempt to access any type of member which has value as null, meaning when we try to access a variable that holds no value or a null value, Null Reference exception will be thrown. This exception is applied for various releases of .NET, .NET Core, and .Net Framework. These reference variables in C# are quite matching with the concepts pf pointers in C. There are various situations when the NullReferenceException occurs and there are multiple ways to avoid or solve it.

Syntax:

Follow is the standard syntax used for the implementation of the NullReferenceException:

public class NullReferenceException :SystemException

The Null Reference Exception is inherited from System Exceptions which basically can be found within Object and into Exception. As we know this is one of the most common exception and there are various ways to handle it.

How NullReferenceException Works in C#?

To simply understand, a Null Reference Exception is a result of an event where we try to access a variable that is not referencing any other object. Now, referring to a reference isn’t a problem here, but when a reference variable is not referencing any other object, then it is basically treated as null. This is where the problem arises when the code is referenced to a point which ends up into a null, then we are encountered with an exception, named NullReferenceException. There can be various scenarios where a Null Reference Exception is thrown by the program. When we execute a program and if it encounters the null reference exception, the output will be something like this:

Unhandled Exception:
System.NullReferenceException: Object reference not set to the instance of the object.

Examples

Now that we have understood what the exception is about and how it works, let us move to properly demonstrating the exception with examples. For our first example, which is very simple, we have a simple variable that holds null value and then we will attempt to work do that variable, but being a null, it will throw the Null Reference Exception. The code for the program is as follows:

Code:

using System;
public class SampleProgram {
public static void Main()     {
string name = null;
varval =name.ToString();
Console.WriteLine(val);
}
}

Code Explanation: Stated with using System, we have our class Sample which is public. Then we have our static void main statement, followed by the creation of a simple string variable named name and value assigned is null, meaning no value to the variable. This string variable is important here, later we create another variable named val, where we attempt to convert the value of name into a string. Finally, we have out a print statement that will print the value of name, which is now converted using ToString(). Refer the below attached screenshot for output:

Output:

C# NullReferenceException-1.1

If executed properly, the code will throw an error, which will be NullReferenceException. And the reason will be that when we are trying to call the ToString() method, it will go to the variable name, but our variable name has no value, meaning null. And as we know, the null value can’t be converted using ToString(). So our code will only print an error, which means code is running as expected.

As explained the program has been terminated by an exception. Moving on, we will demonstrate another simple example, which as explained lead to the same exception.

Code:

using System;
class SampleProgram {
static void Main() {
string val = null;
if (val.Length == 0) {
Console.WriteLine(val);
}
}
}

Code Explanation: Similar to our first example, here we have our namespace and first call, which holds the main statement. Then we have our string variable with value as null. This will be the major variable, which will lead to our expected exception. Then we have a simple if condition where we will check if the length of our variable is zero or not and if it is zero it will move to the next step and print the value. But the code will not move to the final print line as it will encounter an exception while within the if. Refer the below attached screenshot for output:

Output:

Output-1.2

Here, the output is just as our first example, “Unhandled Exception” because the exception is the same, we tried to implement a function here but as explained our variable has a null value which leads us to Null Reference Exception. Now that we have seen and understood how and why this null reference exception occurs, it is important to understand how we can avoid it for better functioning of the program.

How to Avoid NullReferenceException in C#?

The Null Reference Exception is not a major error, but one of the common ones and one of the basic and simple way to avoid the Null Reference Exception is to check the variable or property before moving ahead and accessing it. And a very basic way to do this is to check the variable within an if statement. We will demonstrate an example where we will avoid the occurrence of the exception and the code will move on.

Code:

using System;
class SampleProgram {
static void Main() {
string val = null;
if (val == null) {
Console.WriteLine("n Value to the variable is null.");
}
else{
Console.WriteLine(val);
}
}
}

Output:

0utput-1.3

Code Explanation: Here we have our class which holds the main statement than a variable with a null value. Then we enter an if else statement, where the value of the variable is checked if it is null, the print statement will be printed and the program will terminate, if the value is not null, then it will move ahead and into else part, it will print the value. As expected our code printed that “Value to the variable is null.” because the value is null. If we try the same example with a string value, the program will proceed and the else part will be printed.

Conclusion

The NullReferenceException is encountered when we attempt to access a variable which holds a null value, it can be variable or object. The reference should not hold null value else the exception will be thrown. There are many situations where this can be seen and the simplest way to avoid the NullReferenceException is to check beforehand, before accessing the value.

Recommended Articles

This is a guide to C# NullReferenceException. Here we also discuss the introduction and how nullreferenceexception works in c# along with examples and its code implementation. You may also have a look at the following articles to learn more –

  1. C# Anonymous Functions
  2. C# SortedSet
  3. C# finally
  4. C# SortedList


This post is days old.

I have been working as a software developer for almost three years, the most common exception or bug I made is NullReferenceException —System.NullReferenceException: Object reference not set to an instance of an object. This exception is thrown when you try to access any properties / methods/ indexes on a type of object which points to null.

Common Scenario 1:

using System; 

public class Program
{
    public static void Main()
    {
          string dog = null;
	   var value = dog.ToString(); //Object reference not set to an instance of an object
   	   Console.WriteLine(value);
    }
}

In the example above, we try to call the ToString() method, it will throw a NullReferenceException because dog is pointing to null.

Common Scenario 2:

using System;

public class Dog
{
    public string Breed { get; set; }
    public int Age { get; set; }
}

public class Dogs
{
    public Dog Dog { get; set; }
}

public class Example
{
    public static void Main()
    {
        Dogs dog1 = new Dogs();
        int dogAge = dog1.Dog.Age; // Object reference not set to an instance of an object
	   
        Console.WriteLine(dogAge.ToString());  
    }
}

In the example above, you will get NullReferenceException because Dogs property is null, there is no way to get the data.

Solutions:

NullReferenceException can be very frustating during development, so how can we avoid NullReferenceException?

The solution is very simple, you have to check for every possible null exception property before accessing instance members.

Here are few useful methods:

Method 1 — use if statement

Check the property before accessing instance members.

If (dogs == null)
{
 // do something
}

Method 2 — use Null Conditional Operator(?)

It will check the property before accessing instance members.

int? dogAge = dog1?.Dog?.Age;

Method 3 — use GetValueOrDefault()

It will set a default value if the value is null.

int dogAge = Age.GetValueOrDefault();

Method 4 — use Null Coalescing Operator

You can set a custom value by using ?? if the value is null

var DefaultAge = 5;
int dogAge = dog1?.Dog?.Age ?? DefaultAge

Method 5 — use ?: operator

var DefaultAge = 5;
var IsDogAgeNull = dog1?.Dog?.Age == null;

int dogAge = IsDogAgeNull ?  DefaultAge : dog1?.Dog?.Age;

C# 8 brings a pretty neat feature — Nullable reference types to solve the NullReferenceException issue.

You will need to add the follow code into <PropertyGroup> in your .csproj

<LangVersion>8.0</LangVersion>
<NullableContextOptions>enable</NullableContextOptions>

and then you can do something like

Dog? dog = null; // nullable enable

I hope you found this post helpful, and let me know if you have another good way to handle the NullReferenceException.

Published Mar 10, 2020 by

Suggested reading

Понравилась статья? Поделить с друзьями:
  • System not configured please connect diag tool как исправить
  • System net webexception удаленный сервер возвратил ошибку 404 не найден
  • System net webexception удаленный сервер возвратил ошибку 403 запрещено
  • System net webexception the remote server returned an error 500 internal server error
  • System net webexception the remote server returned an error 404 not found