What is a NullReferenceException, and how do I fix

2019-04-16 16:57发布

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 to fix this error?

30条回答
孤傲高冷的网名
2楼-- · 2019-04-16 17:40

While what causes a NullReferenceExceptions and approaches to avoid/fix such an exception have been addressed in other answers, what many programmers haven't learned yet is how to independently debug such exceptions during development.

In Visual Studio this is usually easy thanks to the Visual Studio Debugger.


First, make sure that the correct error is going to be caught - see How do I allow breaking on 'System.NullReferenceException' in VS2010? Note1

Then either Start with Debugging (F5) or Attach [the VS Debugger] to Running Process. On occasion it may be useful to use Debugger.Break, which will prompt to launch the debugger.

Now, when the NullReferenceException is thrown (or unhandled) the debugger will stop (remember the rule set above?) on the line on which the exception occurred. Sometimes the error will be easy to spot.

For instance, in the following line the only code that can cause the exception is if myString evaluates to null. This can be verified by looking at the Watch Window or running expressions in the Immediate Window.

var x = myString.Trim();

In more advanced cases, such as the following, you'll need to use one of the techniques above (Watch or Immediate Windows) to inspect the expressions to determine if str1 was null or if str2 was null.

var x = str1.Trim() + str2.Trim();

Once where the exception is throw has been located, it's usually trivial to reason backwards to find out where the null value was [incorrectly] introduced --

Take the time required to understand the cause of the exception. Inspect for null expressions. Inspect the previous expressions which could have resulted in such null expressions. Add breakpoints and step through the program as appropriate. Use the debugger.


1 If Break on Throws is too aggressive and the debugger stops on an NPE in the .NET or 3rd-party library, Break on User-Unhandled can be used to limit the exceptions caught. Additionally, VS2012 introduces Just My Code which I recommend enabling as well.

If you are debugging with Just My Code enabled, the behavior is slightly different. With Just My Code enabled, the debugger ignores first-chance common language runtime (CLR) exceptions that are thrown outside of My Code and do not pass through My Code

查看更多
祖国的老花朵
3楼-- · 2019-04-16 17:40

A NullReferenceException is thrown when we are trying to access Properties of a null object or when a string value becomes empty and we are trying to access string methods.

For example:

  1. When a string method of an empty string accessed:

    string str = string.Empty;
    str.ToLower(); // throw null reference exception
    
  2. When a property of a null object accessed:

    Public Class Person {
        public string Name { get; set; }
    }
    Person objPerson;
    objPerson.Name  /// throw Null refernce Exception 
    
查看更多
冷血范
4楼-- · 2019-04-16 17:43

Another general case where one might receive this exception involves mocking classes during unit testing. Regardless of the mocking framework being used, you must ensure that all appropriate levels of the class hierarchy are properly mocked. In particular, all properties of HttpContext which are referenced by the code under test must be mocked.

See "NullReferenceException thrown when testing custom AuthorizationAttribute" for a somewhat verbose example.

查看更多
叛逆
5楼-- · 2019-04-16 17:43

There is a scenario that can happen that is Class related. The question ended up getting closed prior to my stating the resolution: https://stackoverflow.com/questions/43348009/unable-to-instantiate-class

Beware of classes not instantiating: If any part of your constructor in a class throws a null reference exception the class does not instantiate. In my case it was trying to get a connection string from the web.config that that did not exist.

I instantiated a class:

ClassName myClass = new ClassName();
myClass.RunSomeMethod();

Inside the class itself was a call to get a connection string from the web.config. This part of the constructor threw an null value exception so myClass was null.

If you ever have a situation where a class in not instantiating, try making sure that no part of the class constructor Is throwing a null value exception. F-11 and step through the class and make sure there are no nulls.

查看更多
Root(大扎)
6楼-- · 2019-04-16 17:44

If one is getting this message during saving or compiling the build, just close all the files and then open any file to compile and save.

For me the reason was that I had rename the file and old file was still open.

查看更多
霸刀☆藐视天下
7楼-- · 2019-04-16 17:45

If we consider common scenarios where this exception can be thrown, accessing properties withing object at the top.

Ex:

string postalcode=Customer.Address.PostalCode; 
//if customer or address is null , this will through exeption

in here , if address is null , then you will get NullReferenceException.

So, as a practice we should always use null check, before accessing properties in such objects (specially in generic)

string postalcode=Customer?.Address?.PostalCode;
//if customer or address is null , this will return null, without through a exception
查看更多
登录 后发表回答