String.IsNullOrEmpty() Check for Space

后端 未结 2 587
一个人的身影
一个人的身影 2020-12-31 03:23

What is needed to make String.IsNullOrEmpty() count whitespace strings as empty?

Eg. I want the following to return true instead of the usu

2条回答
  •  -上瘾入骨i
    2020-12-31 03:47

    String.IsNullOrEmpty(" ")
    

    ...Returns False

    String foo = null;
    String.IsNullOrEmpty( foo.Trim())
    

    ...Throws an exception as foo is Null.

    String.IsNullOrEmpty( foo ) || foo.Trim() == String.Empty
    

    ...Returns true

    Of course, you could implement it as an extension function:

    static class StringExtensions
    {
        public static bool IsNullOrWhiteSpace(this string value)
        {
            return (String.IsNullOrEmpty(value) || String.IsNullOrEmpty(value.Trim()));
        }
    }
    

提交回复
热议问题