2

Possible Duplicate:
Why does “abcd”.StartsWith(“”) return true?

Something similar to this being true caught us out:

"FooBar".StartsWith(string.Empty)

Firstly I don't think it should be true but I am also not quite sure why it is true, looking at the "Reflector'ed" code:

public bool StartsWith(string value, bool ignoreCase, CultureInfo culture)
{
    if (value == null)
    {
        throw new ArgumentNullException("value");
    }
    if (this == value)
    {
        return true;
    }
    CultureInfo info = (culture == null) ? CultureInfo.CurrentCulture : culture;
    return info.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}

ignoreCase is false and culture is null. So why does "this == value" evaluate to true?

Community
  • 1
  • 1
NetRunner
  • 149
  • 1
  • 8

3 Answers3

4

It's not that this == value returns true, but CompareInfo.IsPrefix is documented as returning true for String.Empty:

Every string starts and ends with an empty substring (""); therefore, if prefix is an empty string, this method returns true.

一二三
  • 21,059
  • 11
  • 65
  • 74
0

Why do you think "this == value" evaluate to true? I believe this behavior is correct. Any string may be considered to be starting with empty string.

Snowbear
  • 16,924
  • 3
  • 43
  • 67
0

Actually FooBar starts with string.Empty. Any string can be considered starting with string.Empty, as well as 0+a = a.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115