Reinventing The Wheel

Strings Tutorial

In .NET, strings are immutable, which means they cannot be changed.
They are also reference types which means when you create a string, the string object is created on the heap, with a reference to its memory location on the stack.

When you create a string without using the "new" operator, the CLR will first find a matching string,
and if it finds one, it will create a new reference which points to the same string on the heap.
Which is why in the first method "TestStrings1()" in the code below, they are not only the same value, but also the same object.

In "TestStrings2()" however, you are explicitly creating a new object using the "new" operator.
This means that there will be two string objects on the heap. So the strings have the same value, but are different objects.

To understand this better, run the code below in a C# Console Application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace str
{
    class Program
    {
        static void Main(string[] args)
        {
            TestStrings1();
            Console.WriteLine("\n\n");
            TestStrings2();
            Console.Read();
        }

        static void TestStrings1()
        {
            Console.WriteLine("TestStrings1");
            string str1 = "test";
            string str2 = "test";
            if (str1.Equals(str2))
            {
                Console.WriteLine("same value");
            }
            else
            {
                Console.WriteLine("not same value");
            }

            //must use Reference equals method, because with strings only, 
            //== tests if the values are the same, 
            //but for all other classes, == tests if the references are the same.
            if (Object.ReferenceEquals(str1, str2)) 
            {
                Console.WriteLine("same reference");
            }
            else
            {
                Console.WriteLine("not same reference");
            }
        }

        static void TestStrings2()
        {
            Console.WriteLine("TestStrings2");
            string str1 = "test";
            String str2 = new String(str1.ToCharArray());
            if (str1.Equals(str2))
            {
                Console.WriteLine("same value");
            }
            else
            {
                Console.WriteLine("not same value");
            }
            if (Object.ReferenceEquals(str1, str2))
            {
                Console.WriteLine("same reference");
            }
            else
            {
                Console.WriteLine("not same reference");
            }
        }
    }
}
/*
Output:

TestStrings1
same value
same reference



TestStrings2
same value
not same reference
*/