Consider the following simple console application in C # ...

   1: static void Main(string args)
   2: {
   3:     string s1 = "Hello world";
   4:     string s2 = "Hello world";
   5:  
   6:     Console.WriteLine(s1.Equals(s2));
   7:     Console.WriteLine(ReferenceEquals(s1, s2));
   8:     Console.WriteLine(s1 == s2);
   9:  
  10:     string s3 = String.Intern(Console.ReadLine());
  11:  
  12:     Console.WriteLine(s1.Equals(s3));
  13:     Console.WriteLine(ReferenceEquals(s1, s3));
  14:     Console.WriteLine(s1 == s3);
  15:  
  16:     Console.ReadKey();
  17: }

 

who has the following output …

 

string_intern_net

 

As we know the Equals() method and the "==" operator check if the two strings contain the same value while having a different reference (s1 and s2), for which it is obvious the result "True". Why does the ReferenceEquals() provides "True" instead of "False" considering that the two references are different ?

 

Okay ! They are not different in reality !

 

The .Net Framework provides a mechanism of "string interning" and a pool who contains strings that have the same value and avoid unnecessarily memory allocation. For this reason, s1 and s2 are actually the same reference !

 

It 'obvious that, when a string is acquired from the outside it doesn’t happen and you need to explicitly ask the framework to search for the string acquired before the internal pool and possibly allocate a new one if it does not exist ... that is the goal of the String.Intern() method.

 

Let's try to run the same code (unless some changes) on the .Net Micro Framework ...

   1: static void Main(string args)
   2: {
   3:     string s1 = "Hello world";
   4:     string s2 = "Hello world";
   5:  
   6:     Console.WriteLine(s1.Equals(s2));
   7:     Console.WriteLine(ReferenceEquals(s1, s2));
   8:     Console.WriteLine(s1 == s2);
   9:  
  10:     string s3 = String.Intern(Console.ReadLine());
  11:  
  12:     Console.WriteLine(s1.Equals(s3));
  13:     Console.WriteLine(ReferenceEquals(s1, s3));
  14:     Console.WriteLine(s1 == s3);
  15:  
  16:     Console.ReadKey();
  17: }

 

with the following output …

 

string_intern_netmf

 

In this case the ReferenceEquals() confirms that the two reference are different in the first case but also using String.Intern() ... why ?

 

The reason is simple ... the .Net Micro Framework does not support the mechanism of "string interning" and does not provide an internal pool of strings and the answer is as always in the native implementation. Looking into the String.cs file, we find :

   1: public static String Intern(String str)
   2: {
   3:     // We don't support "interning" of strings. So simply return the string.
   4:     return str;
   5: }
   6:  
   7: public static String IsInterned(String str)
   8: {
   9:     // We don't support "interning" of strings. So simply return the string.
  10:     return str;
  11: }

An explicit comment tells us that this feature is not supported !