How does .Net saves string variables whose value is same?

Viewed 103

How does .Net saves string variables whose value is same? For example,

string str1 = “xyz”;
string str2 = “xyz”;

Another scenario is,

string str1 = str2  = str3 = “xyz”;

Will there be a single memory location for both of them or two different memory location?

I was asked about question in one of my recent interviews. As per my understanding, I answered, when value is same then there will be single memory allocated to this value and both str1 and str2 will point to this memory location. Same will happen in second scenario mentioned in the question. But, interviewer was not convinced. Anyone any thoughts on this?

2 Answers

Will there be a single memory location for both of them or two different memory location?

different memory locations. String is a reference type, so both values are stored somewhere. String is an object.

The compiler can choose to optimize string constants however, this is called string interning. In this case you still have 2 references, but they point to the same address.

The Memory is allocated only once due to how CLR uses Intern Pool for duplicate string values. The reference of both the string will be same.

Check reference using - Object.ReferenceEquals(str1, str2);

If you use the code below to get the memory location the references is pointing to it will be same.

string myVar = "This is my string";
        string myVar1 = myVar;

        unsafe
        {
            TypedReference tr = __makeref(myVar);
            IntPtr ptr = **(IntPtr**)(&tr);

            TypedReference tr1 = __makeref(myVar1);
            IntPtr ptr1 = **(IntPtr**)(&tr1);

            Console.WriteLine(ptr);
            Console.WriteLine(ptr1);
        }

enter image description here

The memory location they are pointing to is same. The value is saved in memory only once.

If you assign the same string to other variables then the same reference is taken from the intern pool and assigned to the string variable.

Related