C# checking for null throwing error System.NullReferenceException: 'Object reference not set to an instance of an object.'

enter image description hereHi,

I have the following ef query in my C# code.

        var user = await query
                    .Where(q => q.Email.Equals(email, StringComparison.OrdinalIgnoreCase))
                    .FirstOrDefaultAsync();

        if (user != null) // when i set a debug here i get attached error.
        {
            return user.Id;
        }

This error really confuses me. I am checking for null and it is throwing error at that line of code.

1 answer

  • answered 2022-05-04 10:24 Curt P

    Have you declared the variable user?

    To me this reads like you are trying to test:

    Fetch object, is the value of object 'null'?

    But may be actually testing:

    Fetch object -... there is no object returned. A missing object does not have a value, this operation is undefined - throw error.

    Make sure you have declared/instantiated your user variable before calling this function.

    To test it, declare user = null;

    If the variable is nullable, then your code should execute without error. If user is still not initialised, then the error will move to where you assign null to an undeclared variable.

    _---

    Oh it's async - make sure your async task has finished returning properly before you attempt to use the value.


    I think this may be to do with your async operation or syntax.

    Questions to think about:

    • What is the return type of the async query?
      • Is it nullable?
      • Is it variable?
    • Can you explicitly declare the variable before calling the async query, e.g. declare user as null, then call the query into the declared variable. See if the error still throws, or if it is just the query not returning.
    • Have you declared the async methods correctly, and are you blocking code in the correct place.

    By declaring var user = something; its hard to really be sure what object user actually is. If your query is not returning a Task<> object, then your await may not be blocking.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum