Avatar of skij
skij
Flag for Canada asked on

Test if variable defined without giving "Object reference not set to an instance of an object" error

<%

If (XYZ IsNot Nothing) Then 

 Response.write(XYZ)

End If

%>

Open in new window

This gives me an error:

Server Error in '/' Application.
Object reference not set to an instance of an object.


How can I test if XYZ is actually defined?
ASP.NETVisual Basic.NETVB Script

Avatar of undefined
Last Comment
Paul Jackson

8/22/2022 - Mon
Paul Jackson

Try using the IsNothing() function:
<%

If Not IsNothing(XYZ) Then 

 Response.write(XYZ)

End If

%>

Open in new window

Paul Jackson

You could also use, which probably reads better:

<%

If XYZ Is Not Nothing Then 

 Response.write(XYZ)

End If

%>

Open in new window

Paul Jackson

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
skij

ASKER
That does not work.  I get an error:
Compiler Error Message: BC30451: Name 'XYZ' is not declared.

The problem is that XYZ has not been defined, so checking to see if it is empty causes an error.  
I need to test if it has been defined NOT if it is empty.
Paul Jackson

That error message says it has not been declared not that it has not been defined, there is a difference.
You won't be able to test something if it is not declared.
Testing against Nothing tests whether a reference points to an object not whether the reference exists in the first place.


Can I ask what is XZY and in what situation would it not de declared in the code, not sure I understand the scenario where you need to test against something that isn't declared.

To get rid of the compiler error you have you could turn off option strict in web.config but that is generally not considered good practice:
Change the strict option to false in web.config.

<compilation debug="true" strict="false" explicit="true"/>


You could also turn if off for just that one page by changing the line at the top of the aspx page :


<%@ Page Language="VB" strict="False" %>
skij

ASKER
There is "code behind" code that declares XYZ if certain conditions are met.  The "code behind" code is compiled and I don't have access to it.  I need to test if that code has already been declared or not.  If there is no other way, could "try" and "catch" be used?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
Paul Jackson

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.