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:35

Adding a case when the class name for entity used in entity framework is same as class name for a web form code-behind file.

Suppose you have a web form Contact.aspx whose codebehind class is Contact and you have an entity name Contact.

Then following code will throw a NullReferenceException when you call context.SaveChanges()

Contact contact = new Contact { Name = "Abhinav"};
var context = new DataContext();
context.Contacts.Add(contact);
context.SaveChanges(); // NullReferenceException at this line

For the sake of completeness DataContext class

public class DataContext : DbContext 
{
    public DbSet<Contact> Contacts {get; set;}
}

and Contact entity class. Sometimes entity classes are partial classes so that you can extend them in other files too.

public partial class Contact 
{
    public string Name {get; set;}
}

The error occurs when both the entity and codebehind class are in same namespace. To fix this, rename the entity class or the codebehind class for Contact.aspx.

Reason I am still not sure about the reason. But whenever any of the entity class will extend System.Web.UI.Page this error occurs.

For discussion have a look at NullReferenceException in DbContext.saveChanges()

查看更多
Fickle 薄情
3楼-- · 2019-04-16 17:37

I have a different perspective to answering this. This sort of answers "what else can I do to avoid it?"

When working across different layers, for example in an MVC application, a controller needs services to call business operations. In such scenarios Dependency Injection Container can be used to initialize the services to avoid the NullReferenceException. So that means you don't need to worry about checking for null and just call the services from the controller as though they will always to available (and initialized) as either a singleton or a prototype.

public class MyController
{
    private ServiceA serviceA;
    private ServiceB serviceB;

    public MyController(ServiceA serviceA, ServiceB serviceB)
    {
        this.serviceA = serviceA;
        this.serviceB = serviceB;
    }

    public void MyMethod()
    {
        // We don't need to check null because the dependency injection container 
        // injects it, provided you took care of bootstrapping it.
        var someObject = serviceA.DoThis();
    }
}
查看更多
干净又极端
4楼-- · 2019-04-16 17:38

Another scenario is when you cast a null object into a value type. For example, the code below:

object o = null;
DateTime d = (DateTime)o;

It will throw a NullReferenceException on the cast. It seems quite obvious in the above sample, but this can happen in more "late-binding" intricate scenarios where the null object has been returned from some code you don't own, and the cast is for example generated by some automatic system.

One example of this is this simple ASP.NET binding fragment with the Calendar control:

<asp:Calendar runat="server" SelectedDate="<%#Bind("Something")%>" />

Here, SelectedDate is in fact a property - of DateTime type - of the Calendar Web Control type, and the binding could perfectly return something null. The implicit ASP.NET Generator will create a piece of code that will be equivalent to the cast code above. And this will raise a NullReferenceException that is quite difficult to spot, because it lies in ASP.NET generated code which compiles fine...

查看更多
Animai°情兽
5楼-- · 2019-04-16 17:39

Be aware that regardless of the scenario, the cause is always the same in .NET:

You are trying to use a reference variable whose value is Nothing/null. When the value is Nothing/null for the reference variable, that means it is not actually holding a reference to an instance of any object that exists on the heap.

You either never assigned something to the variable, never created an instance of the value assigned to the variable, or you set the variable equal to Nothing/null manually, or you called a function that set the variable to Nothing/null for you.

查看更多
Juvenile、少年°
6楼-- · 2019-04-16 17:39

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)

查看更多
疯言疯语
7楼-- · 2019-04-16 17:39

Literally the easiest way to fix a NullReferenceExeption has two ways. If you have a GameObject for example with a script attached and a variable named rb (rigidbody) this variable will start null when you start your game.
This is why you get a NullReferenceExeption because the computer does not have data stored in that variable.

I'll be using a RigidBody variable as an example.
We can add data really easily actually in a few ways:

  1. Add a RigidBody to your object with AddComponent > Physics > Rigidbody
    Then go into your script and type rb = GetComponent<Rigidbody>();
    This line of code works best under your Start() or Awake() functions.
  2. You can add a component programmatically and assign the variable at the same time with one line of code: rb = AddComponent<RigidBody>();

Further Notes: If you want unity to add a component to your object and you might have forgotten to add one, you can type [RequireComponent(typeof(RigidBody))] above your class declaration (the space below all of your usings).
Enjoy and have fun making games!

查看更多
登录 后发表回答