Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Session & ViewState Variables validation
Message
General information
Forum:
ASP.NET
Category:
Other
Environment versions
Environment:
VB 9.0
OS:
Vista
Network:
Windows 2008 Server
Database:
MS SQL Server
Miscellaneous
Thread ID:
01344804
Message ID:
01344833
Views:
18
>Hi All,
>
>Throughout my ASP.NET application I am using both Session and ViewState variables. What is a good place to check if the value of the variable used is not equal to NULL in order to prevent from getting the "Object reference not sent to an instance of an object" exception?
>

Immediately before you use it or, if it's used throughout your page you may want to grab it in the Page_Load (or Page_Init) and store it off to a member or property (or use the property itself to do the retrieval - then you can default it to some other value if it's null).

I'd also suggest getting in the habit of only accessing it once (and assigning it to a local variable).

ex.
private string m_myVar;

protected virtual Page_Load(object sender, EventArgs e)
{
   object result = Session["MySessionVar"];
 
   if (result != null)
      this.m_my_Var = result.ToString();
}
Private Dim m_myVar As String

Protected Overridable Sub Page_Load(ByVal sender As object, ByVal e As Eventargs)
   object result = Session("MySessionVar")

   If result <> Nothing Then
      Me.m_myVar = result.ToString()
   End If
End Sub
It doesn't happen very often, but things like Session and Cache can expire between the place where you first check to see if the variable is null and when you then try to use it. By assigning it to something local you avoid that problem (which can be very difficult to find since you're not expecting it).
-Paul

RCS Solutions, Inc.
Blog
Twitter
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform