Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string by value .net? [duplicate]

Tags:

string

.net

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

I declared a class called 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());

Yields:

9  
9

Which I understand because this is an Object = Reference Type and so a and b now reference the same object on the heap.

But what happens here?

 string a1;
 string b1;
 a1 = "Hello";
 b1 = "Goodbye";
 b1 = a1;
 a1 = "Wazzup?";

 Console.WriteLine(a1);
 Console.WriteLine(b1);

This yields:

Wazzup?
Hello

Is String an object who is treated differently?

like image 261
talsegal Avatar asked Mar 27 '26 01:03

talsegal


1 Answers

First, we create two string variables. Right now, they reference nothing because they are not initialized:

string a1;
string b1;

Next, a string with the value "Hello" is created and a reference to that space in memory is returned. a1 is set to that reference:

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

Next, a string with the value "Goodbye" is created, b1 is set to reference to that.

b1 = "Goodbye";

Next we do:

b1 = a1;

This assignment will copy the value of the reference over. Now, b1 points to the string a1 points to, and "Goodbye" is unreachable. Since strings are always allocated on the heap, the garbage collector will eventually stop by and clean up the memory "Goodbye" was using, as nothing refers to it anymore.*

* Edit: Technically this probably isn't true, as string constants would be interned and thus rooted by the interned table - but let's just say these strings came from a database or something.

Next, a string with the value "Wazzup?" is created, a1 is set to a reference to that:

a1 = "Wazzup?";

The "Hello" string is still being referenced by the b1 variable, so it's safe. With all 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 things.

like image 193
Mike Christensen Avatar answered Mar 29 '26 16:03

Mike Christensen