in Technology by
How to fix NullReferenceException in C#?

1 Answer

0 votes
by

Ways to Avoid

Explicitly check for null and ignore null values.

If you expect the reference sometimes to be null, you can check for it being null before accessing instance members:

void PrintName(Person p)
{
    if (p != null) 
    {
        Console.WriteLine(p.Name);
    }
}

Explicitly check for null and provide a default value.

Methods call you expect to return an instance can return null, for example when the object being sought cannot be found. You can choose to return a default value when this is the case:

string GetCategory(Book b) 
{
    if (b == null)
        return "Unknown";
    return b.Category;
}

Explicitly check for null from method calls and throw a custom exception.

You can also throw a custom exception, only to catch it in the calling code:

string GetCategory(string bookTitle) 
{
    var book = library.FindBook(bookTitle);  // This may return null
    if (book == null)
        throw new BookNotFoundException(bookTitle);  // Your custom exception
    return book.Category;
}

Use Debug.Assert if a value should never be null, to catch the problem earlier than the exception occurs.

When you know during development that a method maybe can, but never should return null, you can use Debug.Assert() to break as soon as possible when it does occur:

string GetTitle(int knownBookID) 
{
    // You know this should never return null.
    var book = library.GetBook(knownBookID);  

    // Exception will occur on the next line instead of at the end of this method.
    Debug.Assert(book != null, "Library didn't return a book for known book ID.");

    // Some other code

    return book.Title; // Will never throw NullReferenceException in Debug mode.
}

Use GetValueOrDefault() for nullable value types to provide a default value when they are null.

DateTime? appointment = null;
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the default value provided (DateTime.Now), because appointment is null.

appointment = new DateTime(2022, 10, 20);
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the appointment date, not the default

Use the null coalescing operator: ?? [C#] or If() [VB].

The shorthand to providing a default value when a null is encountered:

IService CreateService(ILogger log, Int32? frobPowerLevel)
{
   var serviceImpl = new MyService(log ?? NullLog.Instance);
 
   // Note that the above "GetValueOrDefault()" can also be rewritten to use
   // the coalesce operator:
   serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;
}

Related questions

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
    What is a NullReferenceException in C#?...
asked Jan 16, 2021 in Technology by JackTerrance
0 votes
    Designing a registration form, and I get this error when adding in MessageBoxButtons and MessageBoxIcon. The error ... for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 15, 2022 in Education by JackTerrance
0 votes
    Designing a registration form, and I get this error when adding in MessageBoxButtons and MessageBoxIcon. The error ... for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 6, 2022 in Education by JackTerrance
0 votes
    How can you fix a broken commit? A. git reset B. git commit –amend C. git fix D. git rebase...
asked Dec 23, 2022 in Technology by JackTerrance
0 votes
    have MS Teams (version 1.4.00.4167 64 bit last updated on 23Feb 21) application installed. When I join the meeting audio ... share the advise here what best can we do to fix this....
asked Mar 10, 2021 in Technology by JackTerrance
0 votes
    What is Cross-Site scripting and how can you fix it?...
asked Feb 16, 2021 in Technology by JackTerrance
0 votes
    How will you fix a Broken Commit?...
asked Nov 4, 2020 in Technology by JackTerrance
0 votes
    I'm pretty new at laravel, in fact and I'm trying to create my very first project. for some ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 27, 2022 in Education by JackTerrance
0 votes
    I'm trying to embed python into a C application. For the moment, I am trying to get the following ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 21, 2022 in Education by JackTerrance
0 votes
    I'm creating my first program on python. The objective is to get an output of trip cost. In the ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 21, 2022 in Education by JackTerrance
0 votes
    I follow step by step when installing kaa single node but I have an error in heck the logs after ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 20, 2022 in Education by JackTerrance
0 votes
    I am attempting to solve a problem where if the elements in one array are squared, and all of the ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 20, 2022 in Education by JackTerrance
0 votes
    I am trying to create authentication using Laravel Passport, I have configured everything the right way as ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 16, 2022 in Education by JackTerrance
0 votes
    I'm creating a button in Tkinter and I wanted to create rounded corners, other posts suggested using an ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 16, 2022 in Education by JackTerrance
...