Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does ReferenceEquals(s1,s2) returns true

Tags:

string

c#

  String s1 = "Hello";
  String s2 = "Hello";

Here s1, s2 are different but then why ReferenceEquals() is returning true

like image 227
user498432 Avatar asked Nov 20 '10 12:11

user498432


People also ask

What is the most accurate way to check for equality by reference?

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.

What does ReferenceEquals stand for?

ReferenceEquals() Method is used to determine whether the specified Object instances are the same instance or not. This method cannot be overridden.


4 Answers

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").

like image 91
Marc Gravell Avatar answered Nov 03 '22 01:11

Marc Gravell


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

like image 28
codezgeek Avatar answered Nov 02 '22 23:11

codezgeek


String is immutable so uses same reference for same value Also see Eric Lippert's blog for all about this.

like image 45
Saeed Amiri Avatar answered Nov 03 '22 01:11

Saeed Amiri


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.

like image 37
alpha-mouse Avatar answered Nov 03 '22 00:11

alpha-mouse