D
D
Denis Bredun2020-07-04 22:06:42
C++ / C#
Denis Bredun, 2020-07-04 22:06:42

What happens when we pass a string to a method and process its value there, given that string is a reference and immutable type?

Let's say we have code:
public static void Main()
{
string str = "str";
Update(str);
Console.WriteLine(str)
}
static void Update(string myStr) => myStr += "S";

What's going on here? We copy the value of the variable str to myStr and everything is the same as with a value type, or we pass a reference to an object of type string, but the string myStr += "S"; just can't change the value of a variable even though it was compiled?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2020-07-04
@Luffy1

Stringtricky type, until recently it could not be set as a constant, because it is indeed a reference type. It is also interned by default, i.e. all identical texts refer to one object. The text cannot be changed, you can only create a new object with new text.
You pass a reference to the "str" ​​object, and then a new text object is created in the method and the reference is stored in a variable.
It follows that if you collect conditional json by constant gluing of texts, then you generate a bunch of new objects - not effectively wasting memory. For this, it is better to use StringBuilder, which puts all the text into one buffer with a larger length in advance.

R
Roman, 2020-07-05
@yarosroman

Nothing will change for you. To protect the line before calling update in the il code, the dup instruction, which duplicates the variable on the stack and passes it to the function, and a reference to the new value will be written to the duplicate variable, and the original variable will not be overwritten.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question