Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does System.String.EndsWith() have a a char overload and System.String.StartsWith() does not?

Tags:

string

c#

.net

char

I was looking through System.String and I was wondering why the EndsWith and StartsWith methods aren't symmetric in terms of parameters they can take.

Specifically, why does System.String.EndsWith support a char parameter while System.String.StartsWith does not? Is this because of any limitation or design feature?

// System.String.EndsWith method signatures
[__DynamicallyInvokable]
public bool EndsWith(string value)

[ComVisible(false)]
[SecuritySafeCritical]
[__DynamicallyInvokable]
public bool EndsWith(string value, StringComparison comparisonType)

public bool EndsWith(string value, bool ignoreCase, CultureInfo culture)

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
internal bool EndsWith(char value)
{
  int length = this.Length;
  return length != 0 && (int) this[length - 1] == (int) value;
}

// System.String.StartsWith method signatures
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[__DynamicallyInvokable]
public bool StartsWith(string value)

[SecuritySafeCritical]
[ComVisible(false)]
[__DynamicallyInvokable]
public bool StartsWith(string value, StringComparison comparisonType)

public bool StartsWith(string value, bool ignoreCase, CultureInfo culture)
like image 708
Ian R. O'Brien Avatar asked Feb 19 '23 04:02

Ian R. O'Brien


1 Answers

Looking in ILSpy, this overload seems overwhelmingly to be called in IO code as

s.EndsWith(Path.DirectorySeparatorChar)

Presumably it's just something the C# team decided it would be useful to have to avoid repetitive code.

Note that it's much easier to make this check at the start (s[0] == c vs s[s.Length - 1] == c) which may also explain why they didn't bother to make a StartsWith overload.

like image 137
Rawling Avatar answered Feb 20 '23 19:02

Rawling