Sunday, January 2, 2011

String Manipulation - IsNullOrEmpty Method

I guess we all need to check strings all around the code. And for that, we have about gazillion ways, and here are some -BAD- examples:
  1. if (ourString == null)
  2. if (ourString == "")
  3. if (ourString.trim() == "")
  4. if (ourString == string.empty)

Luckily, Microsoft have came up with this great method "IsNullOrEmpty" which has something like this:

return val == null || val == String.Empty;

This is a great function thought it doesn't cover 100% of the cases.  Lets say, for example, that I have this string: "    ".

Now, according to Microsoft the IsNullOrEmpty method will return false.
Unfortunately, this is not a good result for us.

In order to fix this in our projects, we added this small method:
public static bool IsNullOrEmpty(this String val)
{
    return val == null || val.trim() == String.Empty;
}

This will resolve our problem.
So now we can use:
bool b = String.IsNullOrEmpty("  ");
And we will get true.

.Net 4 Users:
For you guys Microsoft fixed that thing in the form of
bool b = string.IsNullOrWhiteSpace("   ");
Which will return true.

Good luck
Elad Shalom,
CTO at ITweetLive.com

5 comments:

  1. Any see dial is certainly circle and also hublot replica sale control happen to be trim together with silver-toned. Design and style was initially in line with the traditional sundial. A good ebony calfskin tie, a good metal condition, in addition to a sapphire gemstone see take care of come up with any Art gallery See a good idea any price. Luno. Any Men’s Luno see was initially appears determined by just hublot replica sale predecessor, any Art gallery See. There is similar ebony dial, any jewelry gun within the 12 months o’clock 60 minute block, and also sapphire gemstone see take care of. The two main most obvious discrepancies amongst the shut down cousins are definitely the bracelet and also 60 minute block control. Any Luno’s bracelet is certainly metal, rendering it a good just a bit sportier variant which really can be damaged where you work or simply for execute. Any Luno has also iwc replica uk see control in addition to a gold-plated bezel. Neither of the two see has to be damaged during the standard water, yet, despite the fact that these say they're just water resistant as many as 99 your feet. Junior Sports See. Leaders are usually inaccurate. Extremely, just how many multitude of dollar-sport pieces to get experienced? Certainly, any Movado Sports See is certainly well-designed. It’s composed of similar superior substances together with features as many within their many other pieces. There is any stainless-steel iwc replica sale condition, any scratch-resistant sapphire dial, and also stainlesss steel connection breitling replica sale utilizing hold. Also, it’s maybe not smart to bring it on you choose bright white standard water rafting.

    ReplyDelete