If String with exactly same value are to be optimized to refer to same object then why it is different for below cases:

107 views Asked by At

If String with exactly same value are to be optimized to refer to same object then why it is different for below cases:

        //Case 1:        
        String str1 = "name";
        String str2 = "name";

        if (str1 == str2)
            Console.WriteLine("True"); //Output True
        if (object.ReferenceEquals(str1, str2))
            Console.WriteLine("True"); //Output : True

        //Case 2:
        string hello = "hello";
        string helloWorld = "hello world";
        string helloWorld2 = hello + " world";
        if (helloWorld == helloWorld2)
            Console.WriteLine("True"); //Output : True
        if (object.ReferenceEquals(helloWorld, helloWorld2))
            Console.WriteLine("True"); 
        else
            Console.WriteLine("False"); //Output : False

        //Case 3
        helloWorld2 = "hello world";
        if (helloWorld == helloWorld2)
            Console.WriteLine("True"); //Output : True
        if (object.ReferenceEquals(helloWorld, helloWorld2))
            Console.WriteLine("True"); //Output : True
0

There are 0 answers