Reputation: 931
I need some clarification over the below code. I know that str.Length will return the number of characters in the string.
string str = "Sample string";
int length = str.Length;
My clarification is: Since we are not creating the string object, how the "Sample string" string is assigned to str variable?
Upvotes: 0
Views: 125
Reputation: 48606
The string literal "Sample string"
is created by the compiler, and will be stored in the assembly for you. When you assign it to your reference, you get a reference to that literal string.
There is a ldstr
instruction that specifically loads literal strings from assembly metadata into a string
object reference. It is that reference that has it's Length
property checked.
Upvotes: 4
Reputation: 6432
When you say "Sample String"
in memory a new string object is created the same as if you called new String("Sample String");
. This is just a macro to improve readability.
Upvotes: 0