简体   繁体   中英

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

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)

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.

This is an internal method that only is used in the following 8 methods in mscorlib :

  • System.Security.Util.StringExpressionSet.CanonicalizePath(string path, bool needFullPath):string
  • System.IO.IsolatedStorage.IsolatedStorageFile.DirectoryExists(string path):bool
  • System.IO.Directory.GetDemandDir(string fullPath, bool thisDirOnly):string
  • System.IO.DirectoryInfo.GetDirName(string fullPath):string
  • System.Security.Util.URLString.IsRelativeFileUrl:bool
  • System.IO.DirectoryInfo.MoveTo(string destDirName):void
  • System.IO.DirectoryInfo.Parent:DirectoryInfo
  • System.Globalization.CultureData.SENGDISPLAYNAME:string

Probably just for convenience and code reuse :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM