What is a NullReferenceException, and how do I fix

2020-01-22 07:10发布

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?

28条回答
疯言疯语
2楼-- · 2020-01-22 08:12

Interestingly, none of the answers on this page mention the two edge cases, hope no one minds if I add them:

Edge case #1: concurrent access to a Dictionary

Generic dictionaries in .NET are not thread-safe and they sometimes might throw a NullReference or even (more frequent) a KeyNotFoundException when you try to access a key from two concurrent threads. The exception is quite misleading in this case.

Edge case #2: unsafe code

If a NullReferenceException is thrown by unsafe code, you might look at your pointer variables, and check them for IntPtr.Zero or something. Which is the same thing ("null pointer exception"), but in unsafe code, variables are often cast to value-types/arrays, etc., and you bang your head against the wall, wondering how a value-type can throw this exception.

(Another reason for non-using unsafe code unless you need it, by the way)

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-01-22 08:12

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
查看更多
可以哭但决不认输i
4楼-- · 2020-01-22 08:14

The error line "Object reference not set to an instance of an object. " states that you have not assigned instance object to a object reference and still you are accessing properies/methods of that object.

for example: let say you have a class called myClass and it contains one property prop1.

public Class myClass
{
   public int prop1 {get;set;}
}

Now you are accessing this prop1 in some other class just like below:

public class Demo
{
     public void testMethod()
     {
        myClass ref = null;
        ref.prop1 = 1;  //This line throws error
     }
}

above line throws error because reference of class myClass is declared but not instantiated or an instance of object is not assigned to referecne of that class.

To fix this you have to instantiate (assign object to reference of that class).

public class Demo
{
     public void testMethod()
     {
        myClass ref = null;
        ref = new myClass();
        ref.prop1 = 1;  
     }
}
查看更多
Deceive 欺骗
5楼-- · 2020-01-22 08:17

An example of this exception being thrown is: When you are trying to check something, that is null.

For example:

string testString = null; //Because it doesn't have a value (i.e. it's null; "Length" cannot do what it needs to do)

if (testString.Length == 0) // Throws a nullreferenceexception
{
    //Do something
} 

The .NET runtime will throw a NullReferenceException when you attempt to perform an action on something which hasn't been instantiated i.e. the code above.

In comparison to an ArgumentNullException which is typically thrown as a defensive measure if a method expects that what is being passed to it is not null.

More information is in C# NullReferenceException and Null Parameter.

查看更多
登录 后发表回答