开发者

Bug in C# - "FooBar".StartsWith(string.Empty) is true [duplicate]

This question already has answers here: 开发者_运维百科 Closed 11 years ago.

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?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜