Bug in C# - "FooBar".StartsWith(string.Empty) is true [duplicate]
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.
精彩评论