Goodbye trim()
I’ve been playing a bit the the RC version of the .net framework 4 and already found a new cool method.
Until now when I wanted to check for a valid string I had to use the following code:
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(text.Trim()))
throw newArgumentNullException("text", "text is not valid");
And I had to do that because a string containing nothing but white spaces was not valid and if you called the Trim() method on a null string you’ll get a NullReferenceException, you know the message… (“Object reference not set to an instance of an object.”)
So, the new cool method I found is a static method from string called IsNullOrWhiteSpace. the name pretty much says it all, except that the real name should be IsNullOrEmptyOrWhiteSpaces ;)
Instead of writing the code shown above, where you could easily forget the second condition, now you can have the same behavior in one single sentence:
if (string.IsNullOrWhiteSpace(text))
throw newArgumentNullException("text", "text is not valid");
No comments:
Post a Comment