c# - Object.ReferenceEquals returns true for matching strings -
i using mono , encountered interesting result when comparing references of 2 strings. code below demonstrates example:
using system; class program { static void main() { string s1 = "asd"; string s2 = "asd"; console.writeline("reference equals: {0}", object.referenceequals(s1, s2)); console.readline(); } }
yields true.
it interesting, 2 strings have same value refer 2 different instances. going on?
mono --version : mono jit compiler version 3.2.6 os x 10.9.2
http://msdn.microsoft.com/en-us/library/system.string.intern.aspx
the common language runtime conserves string storage maintaining table, called intern pool, contains single reference each unique literal string declared or created programmatically in program. consequently, instance of literal string particular value exists once in system.
the below shows behavior when strings not created string literal.
static void main(string[] args) { var string1 = new string(new []{'c'}); var string2 = new string(new []{'c'}); console.writeline(string1.equals(string2)); //true console.writeline(object.referenceequals(string1,string2)); //false }
Comments
Post a Comment