string pool

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi!

Is there a string pool in .NET like in Java? Is there any difference between
== and Equals() for string?

If I do the following:
string s1 = "hello";
string s2 = "hello";

Will s2 reference the same object as s1?

Thanks.
 
Vladimir Knezevic said:
Hi!

Is there a string pool in .NET like in Java? Is there any difference
between
== and Equals() for string?

Yes, but not every string gets pooled. See http://tinyurl.com/4vl42 for
details. The Remarks section contains a godd description.
If I do the following:
string s1 = "hello";
string s2 = "hello";

Will s2 reference the same object as s1?

Yes, because string constants are automatically interned by the compiler.
This won't neccessarily work for strings created at runtime.

Niki
 
Its called string interning in .NET and yes, they will reference the same object.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Hi!

Is there a string pool in .NET like in Java? Is there any difference between
== and Equals() for string?

If I do the following:
string s1 = "hello";
string s2 = "hello";

Will s2 reference the same object as s1?

Thanks.
 
As the others have said, .NET has interning too.

But there is another factor to consider re. == vs. Equals:

* In Java, == always compares the references.
* In C#, == can be overloaded and can be given "value" semantics instead of
"reference" semantics, and this is the case with System.String.

So, this gives the following results:

string s1 = "hello";
string s2 = "hello";
string s3 = "hel";
s3 += "lo";

Console.WriteLine(s1 == s2); // True
Console.WriteLine((object)s1 == (object)s2); // True (interning!)
Console.WriteLine(s1 == s3); // True (operator
overloading)
Console.WriteLine((object)s1 == (object)s3); // False (s3 not
interned)

In Java, you would get true, true, false, false instead!

Warning: operator overloading only works if the types are "string" at
compile time!

Bruno.

"Vladimir Knezevic" <[email protected]> a écrit
dans le message de (e-mail address removed)...
 
Back
Top