Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does String.Length work in .NET?

Tags:

c#

.net

I would like to know how the String.Length can count the characters number.
If possible, a simple algorithm would be nice to explain it.

like image 444
user3012958 Avatar asked Dec 08 '22 11:12

user3012958


2 Answers

It doesn't. The number of characters is stored as a field (m_stringLength, if it matters); .Length simply returns this value. In .NET, strings are not typically nul-terminated or similar. The more interesting question is "where is the string data stored" - which is complex; the string type is an exception to the usual rule, and the objects themselves have variable size; the character data is directly inside the string object (it is not the case that the string type has a pointer or reference to the character data; it is the character data, plus a length field).

like image 152
Marc Gravell Avatar answered Dec 11 '22 07:12

Marc Gravell


SystemString.Length does not count characters, it stores the length.

There are two general ways of storing strings - characters+length, and characters+terminator. In .NET the first approach is used; in other languages, such as C, the second approach is used.

like image 44
Sergey Kalinichenko Avatar answered Dec 11 '22 09:12

Sergey Kalinichenko