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 s开发者_StackOverflowtring object, how the "Sample string" string is assigned to str variable?
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.
The compiler is creating the string object for you.
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.
精彩评论