-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?

Community
  • 1
  • 1
NealR
  • 10,189
  • 61
  • 159
  • 299

4 Answers4

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;
    }
}
  • Won't this throw an error if mystring actually is null? – NealR Jan 07 '13 at 22:00
  • 3
    @NealR No, it won't, it will just return `true`. – Servy Jan 07 '13 at 22:01
  • @NealR No, it's evaluating `mystring == null` and then setting `stringIsNull` to that value. To make it more explicit: `bool stringIsNull = (mystring == null)` – Ally Jan 07 '13 at 22:06
  • 2
    @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)` – RobH Jan 07 '13 at 22:24
5

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

if(variable == null)
{
  //do stuff
}
Servy
  • 202,030
  • 26
  • 332
  • 449
3

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

if(str != null)
{

}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2
if (variable != null) 
 //do your action for not null
else 
  //variable is null
apollosoftware.org
  • 12,161
  • 4
  • 48
  • 69