Best C# method for checking for a null string value [duplicate]

二次信任 提交于 2019-12-12 07:02:04

问题


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?


回答1:


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;
    }
}



回答2:


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

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



回答3:


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

if(str != null)
{

}



回答4:


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


来源:https://stackoverflow.com/questions/14204782/best-c-sharp-method-for-checking-for-a-null-string-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!