2

Let,

string a = “Test”;
string b = “test 2”;
string c  = a + b

The output of c is "Testtest 2"

I would like to know how is the memory allocated?

1

1 Answer 1

3
string a = "Test";

You create a reference called a and its pointing to the "Test" object in memory.

string b = "test 2";

You create a reference called b and its pointing to the “test 2” object in memory.

string c  = a + b;

You are allocating new memory address for a + b (and this process uses String.Concat method.) because strings are immutable in .NET. And then c reference assing to this new memory address.

Here is IL code of this;

  IL_0000:  nop
  IL_0001:  ldstr      "Test"
  IL_0006:  stloc.0
  IL_0007:  ldstr      "test 2"
  IL_000c:  stloc.1
  IL_000d:  ldloc.0
  IL_000e:  ldloc.1
  IL_000f:  call       string [mscorlib]System.String::Concat(string,
                                                              string)
  IL_0014:  stloc.2
  IL_0015:  ldloc.2

stloc.0 is used, which stores the value on the top of the evaluation stack into the local memory slot 0.

ldstr instruction is used to load a string into the memory or evaluation stack. It is necessary to load values into evaluation stack before that can be utilized.

The ldloc instruction is a load local instruction. Ldloc places the value of a local variable on the stack.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.