82

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?

2
  • add case if(strSearch != null)? Commented Nov 21, 2011 at 3:03
  • the error indicates an object is null. Either strSearch is null or the result of strSearch.Trim() is null. To check, use Graphain's answer using IsNullOrWhitespace.
    – Russell
    Commented Nov 21, 2011 at 3:04

5 Answers 5

106

The correct way in .NET 4.0 is:

if (String.IsNullOrWhiteSpace(strSearch))

The 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

http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx

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)

The 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

http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx

Indicates whether the specified string is Nothing or an Empty string.

Explanation:

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.SomeMethod() or 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 (String.Empty / "")
  • 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 null.

3
  • 1
    You are missing the closing ) of the if
    – Josh Mein
    Commented Nov 21, 2011 at 3:03
  • +1. But that's only .Net 4.0 or greater. Commented Nov 21, 2011 at 3:03
  • 1
    It's nice to have a class Extension method to do this check: public static IsEmptyOrWhiteSpace(this string value) { return String.IsEmptyOrWhiteSpace(value); Commented Sep 20, 2012 at 8:08
24

All versions of .Net:

if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)

.Net 4.0 or later:

if (String.IsNullOrWhitespace(strSearch))
5

strSearch in this case is probably null (not simply empty).

Try using

String.IsNullOrEmpty(strSearch)

if you are just trying to determine if the string doesn't have any contents.

7
  • This doesn't help if his string contains whitespace. Commented Nov 21, 2011 at 3:07
  • The original question was looking for a 0 length string, so strictly that would be a slightly different requirement. Commented Nov 21, 2011 at 3:09
  • @Handsome Cam: Now I'm getting an error on this line. I think it's not worded correctlly. string strSearch = Request["txtSearchName"].ToString();
    – Mike
    Commented Nov 21, 2011 at 3:09
  • 1
    @Handsome - A 0 length string after calling Trim(). Commented Nov 21, 2011 at 3:10
  • @RitchMelton hah! That's what I get for speed mis-reading! Commented Nov 21, 2011 at 3:11
5

I know this was posted about a year ago, but this is for users for future reference.

I came across similar issue. In my case (i will try to be brief, please do let me know if you would like more detail), i was trying to check if a string was empty or not (string is the subject of an email). It always returned the same error message no matter what i did. I knew i was doing it right but it still kept throwing the same error message. Then it dawned in me that, i was checking if the subject (string) of an email (instance/object), what if the email(instance) was already a null at the first place. How could i check for a subject of an email, if the email is already a null..i checked if the the email was empty, it worked fine.

while checking for the subject(string) i used IsNullorWhiteSpace(), IsNullOrEmpty() methods.

if (email == null)
{     
     break;    
}
else
{    
     // your code here    
}
1
  • 1
    Due to short-circuiting, you can have something like 'if(email == null || email.subject.IsNullOrWhiteSpace()){....', and it should handle the null email part just fine
    – Ross Aiken
    Commented Sep 6, 2013 at 18:13
1

I want to extend MattMitchell's answer by saying you can create an extension method for this functionality:

public static IsEmptyOrWhitespace(this string value) {
    return String.IsEmptyOrWhitespace(value);
}

This makes it possible to call:

string strValue;
if (strValue.IsEmptyOrWhitespace())
     // do stuff

To me this is a lot cleaner than calling the static String function, while still being NullReference safe!

Not the answer you're looking for? Browse other questions tagged or ask your own question.