in Technology by
edited by
What is a NullReferenceException in C#?

1 Answer

0 votes
by

You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all.

Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A".

null can have different meanings:

  1. Object variables which are uninitialized and hence point to nothing. In this case, if you access properties or methods of such objects, it causes a NullReferenceException.
  2. The developer is using null intentionally to indicate there is no meaningful value available. Note that C# has the concept of nullable datatypes for variables (like database tables can have nullable fields) - you can assign null to them to indicate there is no value stored in it, for example int? a = null; where the question mark indicates it is allowed to store null in variable a. You can check that either with if (a.HasValue) {...} or with if (a==null) {...}. Nullable variables, like a this example, allow to access the value via a.Value explicitly, or just as normal via a.
    Note that accessing it via a.Value throws an InvalidOperationException instead of a NullReferenceException if a is null - you should do the check beforehand, i.e. if you have another on-nullable variable int b; then you should do assignments like if (a.HasValue) { b = a.Value; } or shorter if (a != null) { b = a; }.

The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a NullReferenceException.

More Specifically

The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference, and the reference is not initialized (or it was once initialized, but is no longer initialized).

This means the reference is null, and you cannot access members (such as methods) through a null reference. The simplest case:

string foo = null;
foo.ToUpper();

This will throw a NullReferenceException at the second line because you can't call the instance method ToUpper() on a string reference pointing to null.

Debugging

If you want to find out where the reference is or isn't set, right-click its name and select "Find All References". You can then place a breakpoint at every found location and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether you expect the reference to be non-null, inspect the variable, and verify that it points to an instance when you expect it to.

By following the program flow this way, you can find the location where the instance should not be null, and why it isn't properly set.

Examples

Some common scenarios where the exception can be thrown:

Generic

ref1.ref2.ref3.member

If ref1 or ref2 or ref3 is null, then you'll get a NullReferenceException. If you want to solve the problem, then find out which one is null by rewriting the expression to its simpler equivalent:

var r1 = ref1;
var r2 = r1.ref2;
var r3 = r2.ref3;
r3.member

Specifically, in HttpContext.Current.User.Identity.Name, the HttpContext.Current could be null, or the User property could be null, or the Identity property could be null.

Indirect

public class Person 
{
    public int Age { get; set; }
}
public class Book 
{
    public Person Author { get; set; }
}
public class Example 
{
    public void Foo() 
    {
        Book b1 = new Book();
        int authorAge = b1.Author.Age; // You never initialized the Author property.
                                       // there is no Person to get an Age from.
    }
}

Related questions

0 votes
    How to fix NullReferenceException in C#?...
asked Jan 16, 2021 in Technology by JackTerrance
0 votes
    This question's answers are a community effort. Edit existing answers to improve this post. It is not ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 17, 2022 in Education by JackTerrance
0 votes
    Why do we use Async and Await in C#?...
asked Jul 27, 2021 in Technology by JackTerrance
0 votes
    What do you mean by value types and reference types in C#?...
asked Jul 27, 2021 in Technology by JackTerrance
0 votes
    How you can implement nullable types in C#? explain with the syntax of Nullable type....
asked Jul 27, 2021 in Technology by JackTerrance
0 votes
    What is a multicast delegate in C#?...
asked Jul 27, 2021 in Technology by JackTerrance
0 votes
    What is Garbage Collection in C#.Net?...
asked Jul 27, 2021 in Technology by JackTerrance
0 votes
    What is Reflection in C#.Net?...
asked Jul 27, 2021 in Technology by JackTerrance
0 votes
0 votes
    What is the difference between method overloading and method overriding in C#?...
asked Jul 27, 2021 in Technology by JackTerrance
0 votes
    What is the difference between dispose() and finalize() methods in C#?...
asked Jul 27, 2021 in Technology by JackTerrance
0 votes
    What is the difference between abstract class and interface in C#?...
asked Jul 27, 2021 in Technology by JackTerrance
0 votes
    Selenium doesn’t support the following programming language: 1. Python 2. C# 3. C 4. Java...
asked Jul 11, 2021 in Technology by JackTerrance
0 votes
    What are partial classes in C#?...
asked Jul 9, 2021 in Technology by JackTerrance
0 votes
    What are Properties in C#?...
asked Jul 9, 2021 in Technology by JackTerrance
...