title: VB.NET: How to access a session variable from a public class?
body: <p>I'm working on an ASP web application that has both code-behind pages and separate classes not associated with any .asp page.  In the code-behind pages, I manage several different session variables, one of which is Session("debug").  For example:</p>
  
  <pre><code>    'Have we created a session debug variabe yet?  If not, create one!
      If Session("debug") IsNot Nothing Then
          _debug = TryCast(Session("debug"), DebugControl)
      Else
          _debug = New DebugControl
          Session("debug") = _debug
      End If
      'This is the debug control.  Uncomment this to turn debugging on
      _debug.isOn = True
  </code></pre>
  
  <p>In one of the public classes, I attempt to use the session variable programmatically in the class constructor:</p>
  
  <pre><code>    Public Class SQLControl
          Inherits System.Web.UI.MasterPage
              Private _debug As DebugControl
  
              Public Sub New()
                  If HttpContext.Current.Session("debug") Is Nothing Then
                      _debug = New DebugControl
                      HttpContext.Current.Session("debug") = _debug
                  Else
                      _debug = DirectCast(HttpContext.Current.Session("debug"), DebugControl)
                  End If
              End Sub
  </code></pre>
  
  <p>However, when I build the application, I get the following (line 26 is highlighted as the error):</p>
  
  <pre><code>Server Error in '/dev' Application.
  
  Object reference not set to an instance of an object.
  
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
  
  Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
  
  Source Error: 
  
  
  Line 24: 
  Line 25:     Public Sub New()
  Line 26:         If HttpContext.Current.Session("debug") Is Nothing Then
  Line 27:             _debug = New DebugControl
  Line 28:             HttpContext.Current.Session("debug") = _debug
  </code></pre>
  
  <p>I've read several threads describing similar problems, but most of them suggested using the HttpContext.Current.Session() method, which I'm already doing (I've also tried System.Web.HttpContext.Current.Session, with the same results.)  Any thoughts?</p>
  
  <p>Thanks!</p>
  
  <p>David</p>