What's the most efficient way to determine whether an untrimmed string is empty in C#?

前端 未结 8 1617

I have a string that may have whitespace characters around it and I want to check to see whether it is essentially empty.

There are quite a few ways to do this:

8条回答
  •  清歌不尽
    2020-12-16 00:10

    Since I just started I can't comment so here it is.

    if (String.IsNullOrEmpty(myString.Trim()))
    

    Trim() call will fail if myString is null since you can't call methods in a object that is null (NullReferenceException).

    So the correct syntax would be something like this:

    if (!String.IsNullOrEmpty(myString))
    {
        string trimmedString = myString.Trim();
        //do the rest of you code
    }
    else
    {
        //string is null or empty, don't bother processing it
    }
    

提交回复
热议问题