0

I made a new class, and I'm getting a null reference exception, and I cannot figure out why.

Object reference not set to an instance of an object.

    namespace TIMBaseClasses.ReturnerTracking
{
    [Serializable]
    public class Returner
    {
            private Guid _returnerID;
            private string _clientIP;

            public Guid returnerID {get { return _returnerID; } set { _returnerID = value; }}
            public string clientIP {get { return _clientIP; } set { _clientIP = value; }}


            /// <summary>Constructor that sets the default values as needed</summary>
            public Returner()
            {
                returnerID = Guid.Empty;
                clientIP = string.Empty;
            }

            public static Returner Instance
            {
                get
                {
                    var ret = (Returner)(HttpContext.Current.Session["Returner"] ?? new Returner());
                    HttpContext.Current.Session["Returner"] = ret;
                    return ret;
                }
            }


    }
}

The error happens towards the bottom, on the "var ret" line at the end when I call "new Returner()".

The line that calls it that causes the error is as follows.

 Returner.Instance.returnerID = id;

EDIT

To address the concerns that the HTTPContext.Current is null, I did a watch and it is not null. However, a watch on "new Returner()" gives me this:

Instance = 'TIMBaseClasses.ReturnerTracking.Returner.Instance' threw an exception of type 'System.NullReferenceException'
JMD
  • 403
  • 3
  • 6
  • 17
  • 3
    It's possible that `HttpContext.Current` is null if you're calling this from the wrong thread or something like that. – Servy Aug 29 '12 at 18:02

3 Answers3

5

Is HTTPContext.Current non-null? If it is null, you will get a NullReferenceException.

Guvante
  • 18,775
  • 1
  • 33
  • 64
5

Its probably more likely that HTTPContext.Current or HTTPContext.Current.Session is null

Jason Coyne
  • 6,509
  • 8
  • 40
  • 70
  • A watch on the line confirms that it is not null. The Session is null, and the null coalescence operator then shuffles us over to "new Returner()" which is null somehow. – JMD Aug 29 '12 at 18:11
  • The entire session is null? Or just the value returned by Session["ret"] ? – Jason Coyne Aug 29 '12 at 18:14
  • Nevermind. I cleaned and rebuilt and now the error is pointing to the HTTPContext.Current being null, just as you said. Thanks. – JMD Aug 29 '12 at 18:16
  • If you know of a way to get around that being null when calling from a webservice that would be much appreciated. – JMD Aug 29 '12 at 18:23
  • 1
    http://stackoverflow.com/questions/5904313/access-httpcontext-current-from-wcf-web-service – Jason Coyne Aug 29 '12 at 18:29
1

your property HTTPContext.Current is null

Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51