Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it showing NullReferenceException when the variable is not null?

NRE

Why is VS 2012 showing the Type variable as an NullReferenceException when it also shows that it's value = "Retailer".

enter image description here

I've got a newborn, and I'm working on limited sleep, so I apologize if I'm missing something obvious here. The LoggedInUser.Employer object has been instantiated and this line works fine 1/2 of the time. But then it starts breaking. Not sure if this helps - need sleep...

 private string _type;
    public string Type
    {
        get { return _type; }
        set
        {
            if (value != null)
            {
                TypeEnum = (Constants.BusinessType)Enum.Parse(typeof(Constants.BusinessType), value, true);
                _type = value;
            }
        }
    }

enter image description here I'm starting to wonder if it's a cross-thread issue...

enter image description here

like image 244
Jeff Borden Avatar asked Feb 18 '13 01:02

Jeff Borden


People also ask

Why am I getting a NullReferenceException?

This error is caused when an object is trying to be used by a script but does not refer to an instance of an object. To fix this example we can acquire a reference to an instance of the script using GameObject.

How do I stop NullReferenceException?

The Null Reference Exception is not a major error, but one of the common ones and one of the basic and simple way to avoid the Null Reference Exception is to check the variable or property before moving ahead and accessing it. And a very basic way to do this is to check the variable within an if statement.

How do I fix NullReferenceException object reference not set to an instance of an object?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.

What does system NullReferenceException mean?

A NullReferenceException happens when you try to access a reference variable that isn't referencing any object. If a reference variable isn't referencing an object, then it'll be treated as null .


2 Answers

The ASP.NET ExecutionContext, responsible for storing the HttpContext.Current instance, won't naturally "flow" to other threads. Judging by your error stack trace, you're working in ASP.NET MVC, a framework that abstracts away the use of HttpContext. You've perhaps come from a WebForms background, where its direct use is common?

SynchronizationContext

This article offers much more detail than I can reasonably go into. Some of the points most relevant to your situation though are:

"ExecutionContext is all about “ambient” information, meaning that it stores data relevant to the current environment or “context” in which you’re running."

This "ambient" information being... HttpContext.Current and its various properties (including Session).

"This means that this ambient context we’ve come to rely on for controlling details of our execution is no longer viable, because TLS doesn’t “flow” across these async points."

TLS being thread-local-storage (HttpContext.Current, etc.) In short, async = potentially lose HttpContext.Current.

The MVC way

Remember I said MVC mostly abstracts away HttpContext?

Session is in Controller.Session. (I'm sorry to say that as yet I have not tested this in an async controller action, so can't verify it's suitability for your needs as yet, or whether you will need additional work to make it cooperate.)

Request is in Controller.Request

User is in Controller.User

There are others... check them out.

Session Alternatives?

Have you considered alternatives? You don't have to look far to find articles suggesting that Session + ASP.NET MVC is a bad idea. I'm not going to weigh in on something as generalised as whether or not it's a "bad thing", but looking at your example, it seems to me you're dealing with user profile data, not "session" data.

Session isn't really the right place to be caching user profile information. For that matter, is it appropriate to cache it at all? Could a users profile change during a session? If they changed it themselves, would you reset the session? What if a separate admin user changed their profile while they were logged in?

Exploring alternatives are beyond the scope of this question, but just be wary that you may be trying to solve the wrong problem here.

like image 109
Snixtor Avatar answered Sep 28 '22 06:09

Snixtor


String.IsNullOrEmpty won't throw this exception on a string, even if it's null so the Type property is not the issue. LoggedInUser is used 2 lines before without error, so that leaves the Employer property as the culprit (unless String isn't the built in String).

You can add a check for null on that to confirm:

if (LoggedInUser.Employer != null) 
{
    if (String.IsNullOrEmpty(LoggedInUser.Employer.Type))
    {
        ...  
    }
}
else
{
    // debug output
}

Assuming Employer is null, you'll need to provide that property definition here. Because you only see this when multiple users are logged in, I'm suspecting a static declaration somewhere it shouldn't be.

like image 33
Mufaka Avatar answered Sep 28 '22 06:09

Mufaka