7

If string.Empty != null why string.IsNullOrEmpty() is created?

I just want to say that:
if null and string.Empty are different to each other.

  • why string.IsNull(); and string.IsEmpty(); separate methods does not exist.
  • why a combined method string.IsNullOrEmpty() exists?
3
  • 3
    Because checking whether string contains at least one character or not is one of the most common things, so the .NET developers gave us nice shortcut. Commented Jun 26, 2011 at 8:59
  • I'm not happy with my formatting :( can anyone reformat it for me... Commented Jun 26, 2011 at 8:59
  • 1
    Reformat what exactly? Looks just fine to me. Commented Jun 26, 2011 at 9:00

2 Answers 2

15
  • string.IsNull doesn't exist because you'd just check for the reference being null
  • string.IsEmpty doesn't exist because you can easily compare for equality with "" or for a length of 0
  • string.IsNullOrEmpty exists because it's simpler to write the single method call than use

       if (text == null || text.Length == 0)
    

    (or the inverse, of course).

Each of the individual checks can be done simply on its own, but it's convenient to have a combination of the two.

Sign up to request clarification or add additional context in comments.

4 Comments

aahhhh, I don't know why these silly questions comes in my mind...:( thanx @Jon for your answer;
And don't forget .NET 4 adds IsNullOrWhitespace. And this check is more than single line of code.
But when does one need such a function? I rarely encounter situations where one wants to treat null and "" the same way. Encountering null usually implies a programming error and leads to ArgumentNullException and "" can be bad user input which requires completely different behavior. And even if it's a bug it should throw something like ArgumentException
@Yet That question doesn't make much sense IMO. What kind of threading interference are you talking about? Strings are immutable, so once you've read the reference the output of this function is determined by the value of that reference.
1

It's for checking that the input string is a valid one. (e.g, not null and not empty). So you don't want to do both the checks each time you want to ensure that so that's why it is made for. If you want to check either of the single ones you can just use the == null or == "" compares.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.