June 7, 2012

String - Intern Pool

Intern Pool

The common language runtime conserves string storage by maintaining a table, called the Intern pool, that contains a single reference to each unique literal.
Eg:
   1:  using System;
   2:   
   3:  namespace ProveStringIsImmutable
   4:  {
   5:      class Program
   6:      {
   7:          static void Main(string[] args)
   8:          {
   9:              string foo = "I`m a good boy";
  10:              string bar = "I`m a good boy";
  11:              Console.WriteLine(Object.ReferenceEquals(foo, bar));
  12:              foo = foo + " with some stuff";
  13:              Console.WriteLine(Object.ReferenceEquals(foo, bar));
  14:          }
  15:      }
  16:  }
  17:   
  18:  //Output:
  19:  //--------------------
  20:  //true
  21:  //false

Initially foo and bar have unique string literals, so foo and bar got same reference. In Brief While try to assigning bar, CLR smart enough to check the given literals already exists in intern table or not, if yes then, returns same existing memory reference of unique string literals.

Here We can also able to prove string immutability , when we try to alter foo, The resulted reference not match with old one, that means CLR assigned new memory reference for altered string.
"If we try to change or modify a string, it finally ended with entirely new string - String Immutability"

No comments:

Post a Comment

Recommended Post Slide Out For Blogger