What is a NullReferenceException


What is a NullReferenceException, and how do I fix it?

The developer is using null intentionally to indicate there is no meaningful value available. Note that C# has the concept of null able 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,

how do I fix 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 Invalid Operation Exception instead of a Null Reference Exception 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 Null  Reference Exception.


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).

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; 
                                     
    }
}
If you want to avoid the child (Person) null reference, you could initialize it in the parent (Book) object's constructor.

Comments

Popular posts from this blog