String by .net value?

I know that String in .NET is a subclass of Object and that objects in .NET are a reference type. So the following code puzzles me a bit. Can you help me understand the difference? Thanks

I declared the class MyInt:

class MyInt { int i; public int number { get { return i; } set { i = value; } } public override string ToString() { return Convert.ToString(i); } } 

Then the following code:

 MyInt a = new MyInt(); MyInt b = new MyInt(); a.number = 5; b.number = 7; b = a; a.number = 9; Console.WriteLine(a.ToString()); Console.WriteLine(b.ToString()); 

Productivity:

 9 9 

Which I understand, because it is Object = Reference Type, and therefore a and b now refer to the same object on the heap.

But what is going on here?

  string a1; string b1; a1 = "Hello"; b1 = "Goodbye"; b1 = a1; a1 = "Wazzup?"; Console.WriteLine(a1); Console.WriteLine(b1); 

This gives:

 Wazzup? Hello 

Is a String an object that is processed differently?

+4
source share
2 answers

First we create two string variables. Right now they are not referencing anything because they are not initialized:

 string a1; string b1; 

Then a line is created with the value "Hello" and a link is returned to this space in memory. a1 installed in this link:

 a1 = "Hello"; // a1 points to a place in memory with a string containing "Hello" 

Then a line is created with the value Goodbye, b1 is set to refer to it.

 b1 = "Goodbye"; 

Next we do:

 b1 = a1; 

This assignment will copy the value of the link. Now b1 points to the line a1 points to, and goodbye is unavailable. Because strings are always allocated on the heap, the garbage collector eventually stops and clears the memory that Goodbye used because nothing refers to it. *

* Edit: Technically, this is probably not true, since the string constants will be interned and thus embedded in the interned table, but just say that these strings were obtained from the database or something else.

Then a line with the value "Wazzup?", a1 is given by reference to this:

 a1 = "Wazzup?"; 

The string "Hello" still refers to the variable b1 , so it is safe. With that in mind:

 // Prints "Wazzup" because we just set a1 to a reference to that string Console.WriteLine(a1); //Prints "Hello" because b1 still has its value it had copied over from a1 Console.WriteLine(b1); 

Hope this clarifies the situation.

+6
source

Just remember that the changing value of String always creates a new instance of the String class.

for instance

 string test1 = "Test"; // point to memory address "1023" test1 = "New test"; // Now new instance was created and variable point to another memory address 
0
source

Source: https://habr.com/ru/post/1497322/


All Articles