...let John help you code



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

Asked by:
Userneo
Nov 13, 2016, 22:51

Description

I have some code and when it executes, it throws a NullReferenceException , saying:

Object reference not set to an instance of an object.

What does this mean, and what can I do about it?

4 Answers

Answer :
Code

Preview
 

5

If you have not initialized a reference type, and you want to set or read one of its properties, it will throw a NullReferenceException .

Example:

Person p = null;
p.Name = "Harry"; // NullReferenceException occurs here.

You can simply avoid this by checking if the variable is not null:

Person p = null;
if (p!=null)
{
p.Name = "Harry"; // Not going to run to this point
}

To fully understand why a NullReferenceException is thrown, it is important to know the difference between value types and reference types .

So, if you're dealing with value types , NullReferenceExceptions can not occur. Though you need to keep alert when dealing with reference types !

Only reference types, as the name is suggesting, can hold references or point literally to nothing (or 'null'). Whereas value types always contain a value.

Reference types (these ones must be checked):


  • dynamic

  • object

  • string

  • Value types (you can simply ignore these ones):


  • Numeric types

  • Integral types

  • Floating-point types

  • decimal

  • bool

  • User defined structs
  • Frank-en-teins


    2

    What can you do about it?



    There is a lot of good answers here explaining what a null reference is and how to debug it. But there is very little on how to prevent the issue or at least make it easier to catch.

    Check arguments



    For example methods can check the different arguments to see if they are null and throw and ArgumentNullException , an exception obviously created for this exact purpose.

    The constructor for the ArgumentNullException even takes the name of the parameter and a message as arguments so you can tell the developer exactly what the problem is.

    public void DoSomething(MyObject obj) {
    if(obj == null)
    {
    throw new ArgumentNullException("obj", "Need a reference to obj.");
    }
    }

    Use Tools



    There are also several libraries that can help. "Resharper" for example can provide you with warnings while you are writing code, especially if you use their attribute: NotNullAttribute

    There's "Microsoft Code Contracts" where you use syntax like
    Contract.Requires(obj != null)   
    which gives you runtime and compile checking: Introducing Code Contracts.

    There's also "PostSharp " which will allow you to just use attributes like this:

    public void DoSometing([NotNull] obj)  

    By doing that and making PostSharp part of your build process obj will be checked for null at runtime. See: PostSharp null check

    Plain Code Solution



    Or you can always code your own approach using plain old code. For example here is a struct that you can use to catch null references. It's modeled after the same concept as Nullable<T>:

    [System.Diagnostics.DebuggerNonUserCode]
    public struct NotNull<T> where T : class
    {
    private T _value;

    public T Value
    {
    get
    {
    if (_value == null)
    {
    throw new Exception("null value not allowed");
    }

    return _value;
    }
    set
    {
    if (value == null)
    {
    throw new Exception("null value not allowed.");
    }

    _value = value;
    }
    }

    public static implicit operator T(NotNull<T> notNullValue)
    {
    return notNullValue.Value;
    }

    public static implicit operator NotNull<T>(T value)
    {
    return new NotNull<T> { Value = value };
    }
    }

    You would use very similar to the same way you would use Nullable<T >, except with the goal of accomplishing exactly the opposite - to not allow null. Here are some examples:

    NotNull<Person> person = null; // throws exception
    NotNull<Person> person = new Person(); // OK
    NotNull<Person> person = GetPerson(); // throws exception if GetPerson() returns nu
    ll
    NotNull<T> is implicitly casted to and from T so you can use it just about anywhere you need it. For example you can pass a Person object to a method that takes a NotNull<Person> :

    Person person = new Person { Name = "John" };
    WriteName(person);

    public static void WriteName(NotNull<Person> person)
    {
    Console.WriteLine(person.Value.Name);
    }

    As you can see above as with nullable you would access the underlying value through the Value property. Alternatively, you can use explicit or implicit cast, you can see an example with the return value below:

    Person person = GetPerson();

    public static NotNull<Person> GetPerson()
    {
    return new Person { Name = "John" };
    }

    Or you can even use it when the method just returns T (in this case Person) by doing a cast. For example the following code would just just like the code above:

    Person person = (NotNull<Person>)GetPerson();

    public static Person GetPerson()
    {
    return new Person { Name = "John" };
    }

    Combine with Extension



    Combine NotNull<T> with an extension method and you can cover even more situations. Here is an example of what the extension method can look like:

    [System.Diagnostics.DebuggerNonUserCode]
    public static class NotNullExtension
    {
    public static T NotNull<T>(this T @this) where T : class
    {
    if (@this == null)
    {
    throw new Exception("null value not allowed");
    }

    return @this;
    }
    }

    And here is an example of how it could be used:

    var person = GetPerson().NotNull();  
    mod5


    1

    You are using the object that contains the null value reference. So it's giving a null exception. In the example the string value is null and when checking its length, the exception occurred.

    Example:

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

    The exception error is:

    Unhandled Exception:


    System.NullReferenceException: Object reference not set to an instance of an object. at Program.Main()
    Frank-en-teins


    0
    It means that the variable in question is pointed at nothing. I could generate this like so:

    SqlConnection connection = null;
    connection.Open();

    That will throw the error because while I've declared the variable "connection", it's not pointed to anything. When I try to call the member "Open", there's no reference for it to resolve, and it will throw the error.

    To avoid this error:

  • Always initialize your objects before you try to do anything with them.

  • If you're not sure whether the object is null, check it with object == null.

  • JetBrains' Resharper tool will identify every place in your code that has the possibility of a null reference error, allowing you to put in a null check. This error is the number one source of bugs, IMHO.
    Frank-en-teins