Strings are one of the first things that a developer learns about any programming languages. The same thing also applies with C# as well. Although many of us feel that we understand the strings well and make best use of it but sometimes this is not the case. Today I am going to talks one more concepts that is called string interning. I am sure some of you not aware, even I was also not aware few months back. It won’t affect you directly but if you learn it, it will surely make you better developer.
So let's start from the very basic. If we write the below code
Note - One thing you all must be knowing that string objects are immutable. It means the same object cannot be modified and if any operation is being done on a string then a new string is created.
Let’s discuss various scenarios.
- string s1 = "Hi";
- string s2 = "Hi";
But are they same object or both variables s1 and s2 pointing to same memory location?
Let’s just check it.
- Console.WriteLine(Object.ReferenceEquals(s1, s2));
When we execute the above line of code. It displays True. What is the above line actually doing? It checks whether the passed objects are pointing to same memory location or pointing to same object. If points to same object then returns true else false. Pictorially it can be depicted as
Scenario 2:
- string s1 = "Hi Ram";
- string s2 = "Hi " + "Ram";
- Console.WriteLine(Object.ReferenceEquals(s1, s2));
Now what will it print?
True or false?
Confused again. It will print True again. Because it again points to the same object. We'll discuss the reason later in the post.
- string p = "Ram";
- string s1 = "Hi Ram";
- string s2 = "Hi " + p;
- Console.WriteLine(Object.ReferenceEquals(s1, s2));
True? Wrong
Now it’ll print False. In the above code there will be three objects created in memory.
- string s1 = "Hi";
- string s2 = string.Copy(s1);
- Console.WriteLine(Object.ReferenceEquals(s1, s2));

Nitin JainPosted Jun 2, 2019, 3:13 AM
Nice examples and explanation...
kalu singh raoPosted Jul 19, 2016, 2:08 AM
Nice...
gopi krishnaPosted Mar 30, 2016, 7:11 AM
Nice explanation. Thanks!
vikash kumarPosted Sep 18, 2015, 5:40 AM
Awesome
Vithal WadjePosted Sep 26, 2014, 2:00 PM
super keep it up
Guest UserPosted Jul 23, 2014, 7:42 AM
good one Brij!
Manoranjan GuptaPosted Jul 22, 2014, 12:02 AM
Nice article Brij Sir