Effects of immutable strings on reference equality…!


Strings are reference types that behave in many ways like a value type. Assignment and comparison works as you would expect with a value type, because they have value equality implemented, and sometimes they may even have the same reference but, in general, they will behave more like value types. This is a likely source of bugs among novice programmers, since the behaviour may not be immediately obvious.
 
Sample Program
 
string s = "Refference";
            s.ToLower();
            if (object.ReferenceEquals(s, "Refference"))
                Console.WriteLine("They have same reference");
            else
                Console.WriteLine("They have different reference");
            s = s.ToLower();
            if (object.ReferenceEquals(s, "refference"))
                Console.WriteLine("They have same reference");
            else
                Console.WriteLine("They have different reference");
            Console.Read();
Output of the Program

Since strings are immutable, methods from the string class return a new string rather than modify the original string's memory. This can both improve code quality by reducing side effects, and reduce performance if you are not careful.
The first pair of strings has the same reference, because of interning, which we will explain later. The second pair of strings does not have the same reference, because the ToLower method created a new object.
 

No comments:

Post a Comment