Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is String.Length implemented in C#?

Tags:

c#

As per my 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

like image 852
Gyan Avatar asked Jun 28 '11 18:06

Gyan


People also ask

How does C know how long a string is?

Introduction. The string length in C is equal to the count of all the characters in it (except the null character "\0"). For Example, the string "gfddf" has a length of 5 and the string "4343" has a length of 4.

Is there a string length function in C?

strlen() function in c The strlen() function calculates the length of a given string. The strlen() function is defined in string. h header file. It doesn't count null character '\0'.

How strlen is implemented?

strlen function in C/C++ and implement own strlen() The strlen function computes the length of the given string. It takes a string as an argument and returns its length. It doesn't count the null character ( '\0' ).


1 Answers

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).

like image 186
Jon Skeet Avatar answered Sep 23 '22 05:09

Jon Skeet