String s1 = "Hello";
String s2 = "Hello";
Here s1, s2 are different but then why ReferenceEquals() is returning true
To check for reference equality, use ReferenceEquals. To check for value equality, use Equals or Equals. By default, the operator == tests for reference equality by determining if two references indicate the same object, so reference types do not need to implement operator == in order to gain this functionality.
ReferenceEquals() Method is used to determine whether the specified Object instances are the same instance or not. This method cannot be overridden.
This is due to interning - the CLI automatically re-uses strings obtained as literals (i.e. strings that have come directly from your source code). Note that if you did:
char[] chars = {'h','e','l','l','o'};
string s1 = new string(chars);
string s2 = new string(chars);
they would not be the same string instance, as they have not come from literals.
This is documented against the Ldstr
IL instruction:
The Common Language Infrastructure (CLI) guarantees that the result of two ldstr instructions referring to two metadata tokens that have the same sequence of characters return precisely the same string object (a process known as "string interning").
Strings are immutable, once it created in the memory following same String objects are refered to the previously created String object for more http://msdn.microsoft.com/en-us/library/362314fe.aspx
String is immutable
so uses same reference for same value
Also see Eric Lippert's blog for all about this.
You also can use String.Copy(String str)
static method to create strings that will be different objects
String s1 = "Hello";
String s2 = string.Copy("Hello");
then s1 and s2 will be referencing different objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With