string immutability

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi

This is a sample code I am working on.

string a = "rb"
string b = a

Console.WriteLine(Object.ReferenceEquals(a,b))

In the above code, its printing true. I have a doubt on this output. When I say b = a, the system will create a new string called b and copy the value in a to b. Hence b and a should point to two new memory locations. Hence the output should be false, right

Can anybody clarify my doubt

Thanks
 
rb,

This is not correct. Strings are reference types. When you declare b,
you are creating a new variable. When you assign a to b, then you are
copying the reference to a into the variable b. The references are copied,
not the actual object they point to. So, when you make the assignment, b is
pointing to the same thing a is.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

rb said:
Hi,

This is a sample code I am working on.

string a = "rb";
string b = a;

Console.WriteLine(Object.ReferenceEquals(a,b));

In the above code, its printing true. I have a doubt on this output. When
I say b = a, the system will create a new string called b and copy the value
in a to b. Hence b and a should point to two new memory locations. Hence the
output should be false, right.
 
Immutability means when you MODIFY the string it will make a copy.

string b = a;

does not modify any value,

Hi,

This is a sample code I am working on.

string a = "rb";
string b = a;

Console.WriteLine(Object.ReferenceEquals(a,b));

In the above code, its printing true. I have a doubt on this output. When
I say b = a, the system will create a new string called b and copy the value
in a to b. Hence b and a should point to two new memory locations. Hence the
output should be false, right.
 
Jason Wang said:
Immutability means when you MODIFY the string it will make a copy.

No it doesn't. It means you *can't* modify the string. No string
operations change it at all.
 
Hi,

Jason Wang said:
Immutability means when you MODIFY the string it will make a copy.

I think that a clarification is needed regarding immutable.

A class is said to be inmutable when the programmer assure that none of the
methods/properties call will change the instance over which the call is
made, instead a new instance of the same class is created and returned on
those call that would modify the instance.

Also take a look that AFAIK there is no way to mark a type as immutable and
make this enforced by the compiler, therefore you have to trust the
programmer of the type.

Just my 2 cts. :)

Cheers,
 
Back
Top