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:
The
String.IsNullOrWhiteSpacemethod used above is equivalent to:In earlier versions, you could do something like this:
The
String.IsNullOrEmptymethod used above is equivalent to:Which means you still need to check for your “IsWhiteSpace” case with the
.Trim().Length == 0as per the example.Explanation:
You need to ensure
strSearch(or any variable for that matter) is notnullbefore you dereference it using the dot character (.) – i.e. before you dostrSearch.SomeMethod()orstrSearch.SomePropertyyou need to check thatstrSearch != null.In your example you want to make sure your string has a value, which means you want to ensure the string:
String.Empty/"")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
null.