Improving string.IsNullOrEmpty readability

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
777
Location
Norway
Programming Experience
10+
Nullables HasValue mean just null, it doesn't for example mean an int with value 0. Similar an empty string is still a value, but you could argue that a null and empty string compares as equal values.
I would rather name the extension the same as the original though, since it is more accurate and I wouldn't have to think too much about what it actually means in different circumstances.
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,049
Location
Sydney, Australia
Programming Experience
10+
I would rather name the extension the same as the original though, since it is more accurate and I wouldn't have to think too much about what it actually means in different circumstances.
Indeed. Writing IsNotNullOrEmpty and IsNotNullOrWhitespace methods seems the better option. Using HasValue precludes an equivalent for IsNullOrWhitespace so you back yourself into a corner on that.
 

Sheepings

Senior Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,378
Location
UK
Programming Experience
10+
To avoid the null exception in the string. An exception will be thrown if you access str.Length :
C#:
            string str = null;
            bool x = str.Length > 0;
You can do :
C#:
            string str = null;
            bool x = str?.Length > 0;
 
Top Bottom