-1

Possible Duplicate:
How to check if String is null

I need to be able to check for a null value, only, inside a string. The best method I am currently aware of is String.IsNullOrEmpty(), which does not fit what we are trying to do (string.empty values are allowed, nulls are not). Does anyone have any suggestions?

3
  • you should check this out stackoverflow.com/questions/7553567/… Commented Jan 7, 2013 at 22:02
  • why not use the IsNullOrEmpty check..? Commented Jan 7, 2013 at 22:05
  • @DJKRAZE: OP has explained that, because String.Empty is ok whereas null is not. Commented Jan 7, 2013 at 22:11

4 Answers 4

12

just compare your string to null

bool stringIsNull = mystring == null;

here's an extension method for you

public static class ExtensionMethods
{
    public static bool IsNull(this string str)
    {
        return str == null;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Won't this throw an error if mystring actually is null?
@NealR No, it won't, it will just return true.
@NealR No, it's evaluating mystring == null and then setting stringIsNull to that value. To make it more explicit: bool stringIsNull = (mystring == null)
@NealR Extension methods are really just static methods. So in the case of this extension method: string a = null; a.IsNull() // true - no exception thrown is just really doing string a = null; ExtensionMethods.IsNull(a)
5

You check the same way you check if any other variable is null:

if(variable == null)
{
  //do stuff
}

Comments

3

If you want to skip null values, simply use != null:

if(str != null)
{

}

Comments

2
if (variable != null) 
 //do your action for not null
else 
  //variable is null

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.