1

Below is my test case. Both string are different object yet the my test case pass.

I am expecting them to fail. Because they are different objects.

 string string1 = "Hello World";
    string string4 = "Hello World";
    Assert.AreSame(string1, string4);//Will return true
    Assert.IsTrue(object.ReferenceEquals(string1,string4));
maxspan
  • 13,326
  • 15
  • 75
  • 104

2 Answers2

8

Compiler will create one "object" for equal hardcoded strings.

But if you create strings dynamically

var string1 = "Hello World";
var name = "World";
var string2 = "Hello " + name;
Assert.AreSame(string1, string2); //Will return false
Assert.IsTrue(object.ReferenceEquals(string1,string2)); // Fail
Assert.AreEqual(string1, string2); // Pass

String.Intern Method (String)

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

Fabio
  • 31,528
  • 4
  • 33
  • 72
1

When comparing strings. If objA and objB are strings, the ReferenceEquals method returns true if the string is interned. It does not perform a test for value equality.

In the following example, s1 and s2 are equal because they are two instances of a single interned string. However, s3 and s4 are not equal, because although they are have identical string values, that string is not interned.

String s1 = "String1";
String s2 = "String1";
//string is interned

String suffix = "A";
String s3 = "String" + suffix;
String s4 = "String" + suffix;  
//string is not interned
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70