Link to home
Start Free TrialLog in
Avatar of skij
skijFlag 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?
Avatar of Paul Jackson
Paul Jackson
Flag of United Kingdom of Great Britain and Northern Ireland image

Try using the IsNothing() function:
<%

If Not IsNothing(XYZ) Then 

 Response.write(XYZ)

End If

%>

Open in new window

You could also use, which probably reads better:

<%

If XYZ Is Not Nothing Then 

 Response.write(XYZ)

End If

%>

Open in new window

Avatar of 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.
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" %>
Avatar of 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?
ASKER CERTIFIED SOLUTION
Avatar of Paul Jackson
Paul Jackson
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial