0

I have below code in C# Console Application:

        string a = "1";
        string b = a;
        a = "2";
        Console.WriteLine(b);

I heard that in C# the string type works as reference type but in upper code the variable b still shows me 1 and why it does not show me 2 !?

Mostafa
  • 658
  • 7
  • 24

2 Answers2

9

Because you are copying the reference. Strings are immutable, so the only way to change the string is to replace it by a different one. And that is what you are doing with a = "2".

After that, there are two strings in memory: "1" and "2". a points to the latter one but b was assigned a copy of the reference to "1" so that is what you get when you print out a.

poke
  • 369,085
  • 72
  • 557
  • 602
3

Stings are immutable and work like value types but are not (internally they are indeed read only reference types). That's something fundamental and about every doc about .NET is explaining it. Also strings cannot be inherited. It's simple - strings cannot be altered in any way. Every function that seems to alter a string in reality creates a new one.

There is the StringBuilder class that can be used for manipulating strings.

For more info: https://learn.microsoft.com/en-us/dotnet/api/system.string

also see: In C#, why is String a reference type that behaves like a value type?

Daniel Schmid
  • 647
  • 6
  • 12