Is string.Length in the current C # variable (.NET)?

I am wondering if string.Length in C # is an instant variable. By means of an instant variable, I mean when I create a line:

 string A = ""; A = "Som Boh"; 

Is the length calculated?

OR

Is it calculated only after I try to get A.Length?

+6
string c #
source share
4 answers

First, note that strings in .NET are very different from strings stored in unmanaged languages ​​(such as C ++) ... In the CLR, the length of the string (in characters and bytes) is actually stored in memory so the CLR knows how large is the block of memory (an array of characters) containing the string. This is done when the string is created and does not change, given that the type System.String is immutable.

In C ++, this is completely different, since the length of the string is detected by reading to the first null character. Because of how memory usage works in the common language runtime, you can essentially assume that getting the Length property of a string is similar to retrieving an int variable. The cost of execution here will be absolutely minimal if that is what you are considering.

If you want to learn more about strings in .NET, try John Skeet's article on this topic - it looks like all the details you can ever learn about strings in .NET.

+14
source share

The length of the string is not calculated; it is known at build time. Since String is immutable, there is no need to evaluate it later.

The .NET string is stored as a field containing the number of characters and the corresponding Unicode character sequence.

+9
source share

.NET strings are stored with a pre-calculated length and stored at the beginning of the internal structure, so the .Length property simply retrieves this value, making it an O (1) function.

+3
source share

This seems to be a string property, which is probably set in the constructor. Since this is not a function, I doubt that it is calculated when you call it. They simply get the value of the Length property.

+1
source share

All Articles