Request.Cookies?

A

Arpan

An ASPX page has the following code:

Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
If Not (IsNothing(Request.Cookies("AuthCookie"))) Then
Response.Write(Request.Cookies("AuthCookie").Value)
Else
Response.Write(Cookie 'AuthCookie' Doesn't Exist!)
End If
End Sub

Assume that the cookie named "AuthCookie" doesn't exist. As expected,
the Response.Write line in the Else condition gets rendered but if I
change the If condition to

If Not (IsNothing(Request.Cookies("AuthCookie").Value)) Then

then ASP.NET generates the following error:

Object reference not set to an instance of an object.

Why? Is it because Request.Cookies("AuthCookie").Value evaluates to an
expression?

Thanks,

Arpan
 
M

Mark Fitzpatrick

This throws an error because you can't access a property of an object that
doesn't exist. Value is a property, but since the object itself doesn't
exist there cannot be any property for it. You always have to test to see if
the object exists first, which is what you are doing initially, and only
after you test to see if the object itself exists can you attempt to access
a value.

Hope this helps,
Mark Fitzpatrick
Microsoft MVP- FrontPage
 
A

Arpan

Thanks, Mark....your explanation has indeed been very very helpful.

One more question please - to test the existence of an object, I can
use "IsNothing" (as I did in post #1) & also "Is Nothing" like

If (Request.Cookies("AuthCookie") Is Nothing) Then

What I would like to know is are there any performance benefits of one
over the other? Or any other differences between "IsNothing" & "Is
Nothing"? Which among the 2 is more recommended?

Thanks once again,

Regards,

Arpan
 
E

Edwin Knoppert

c#
== null

Arpan said:
Thanks, Mark....your explanation has indeed been very very helpful.

One more question please - to test the existence of an object, I can
use "IsNothing" (as I did in post #1) & also "Is Nothing" like

If (Request.Cookies("AuthCookie") Is Nothing) Then

What I would like to know is are there any performance benefits of one
over the other? Or any other differences between "IsNothing" & "Is
Nothing"? Which among the 2 is more recommended?

Thanks once again,

Regards,

Arpan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,151
Latest member
JaclynMarl
Top