Posted By: Anonymous
I keep getting this error when I run the program.
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 with error: Line 156: if (strSearch == "" || strSearch.Trim().Length == 0)
What is the correct way it should be written?
The correct way in .NET 4.0 is:
String.IsNullOrWhiteSpace method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty || strSearch.Trim().Length == 0) // String.Empty is the same as ""
Reference for IsNullOrWhiteSpace method
Indicates whether a specified string is Nothing, empty, or consists
only of white-space characters.
In earlier versions, you could do something like this:
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)
String.IsNullOrEmpty method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty)
Which means you still need to check for your “IsWhiteSpace” case with the
.Trim().Length == 0 as per the example.
Reference for IsNullOrEmpty method
Indicates whether the specified string is Nothing or an Empty string.
You need to ensure
strSearch (or any variable for that matter) is not
null before you dereference it using the dot character (
.) – i.e. before you do
strSearch.SomeProperty you need to check that
strSearch != null.
In your example you want to make sure your string has a value, which means you want to ensure the string:
- Is not null
- Is not the empty string (
- Is not just whitespace
In the cases above, you must put the “Is it null?” case first, so it doesn’t go on to check the other cases (and error) when the string is