#479 – Identical String Literals Are Stored in the Same Object

The C# compiler will store equivalent string literals in the same underlying System.String object.

In the example below, s1 and s2 refer to the same string literal, so they will share the same underlying System.String object.  s3 will get the same string value assigned to it at runtime, but will be stored in a different object.

            string s1 = "Popeye";    // s1 & s2 will refer to the same
            string s2 = "Popeye";    //   underlying object

            // Enter "Popeye" for s3.  It will be stored in a
            //   different object, though equivalent to s1 & s2.
            string s3 = Console.ReadLine();

            object o1 = s1;
            object o2 = s2;
            object o3 = s3;

            bool bEqual = (o1 == o2);    // True, same object
            bEqual = (o1 == o3);         // False, different objects

We don’t normally care about whether two equivalent strings are stored in the same or different objects, because the == operator for System.String always checks for string equivalence, rather than object identity.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment