How is String.Length implemented in C#?
As per my开发者_JS百科 understanding, there is no null-termination at the end of a C# string. So how does Length get to know how many characters a string have?
Thanks, Gyan
It's stored in a field within the object.
As it happens, strings are null-terminated internally in the current implementation of .NET, but that's only for the sake of interop, so that code which does expect null-terminated strings can be given the same chunk of memory to work with.
Note that having it in a field is a good idea in terms of performance anyway - it makes finding the length an O(1) operation instead of O(N).
精彩评论