Geeks With Blogs
finally{} My interactions with .Net and Web development - What's most important is what happens finally{}

This apparently confusing question has the following answer.

Even though a string is a reference type, it behaves as a value type.

when you assign a value to a string it does not change the undelying object reference, it creates a new one and assigns the string pointer to the new string object.
string strObject1 = "A"
string strObject2 = "B"
string strObject3 = "A"

At this point strObject1 and strObject3 point to the same point in memory.

strObject3="B"

now strObject1 has been unaffected and points to the same place in memory. strObject2 remains pointing at the same point in memory as before. strObject3 now points to the same memory location as strObject2. Note that this is only for String. Not for an object type.

Maybe "strObject2.Equals(strObject3)" is still looking if they are the same place in memory?  If they are on different machines, it isn't the same place in memory.

I would use "String.Compare" since that compares the strings value instead of the memory location.

strObject1 == strObject2 does a value compare as well.

Conclusion:

.Equals compares values not references in strings. Else compares references.

== always does a value compare.

Posted on Thursday, September 22, 2005 4:57 PM .Net Framework , C# | Back to top


Comments on this post: strObject1.Equals(strObject2) v/s strObject1 == strObject2

# re: strObject1.Equals(strObject2) v/s strObject1 == strObject2
Requesting Gravatar...
String literals are special. Try again with

string strObject3 = 'A'.ToString();

Don't forget to use object.ReferenceEquals to test for reference identity.
Left by Raymond Chen on Sep 22, 2005 9:05 PM

Your comment:
 (will show your gravatar)


Copyright © Vinayak | Powered by: GeeksWithBlogs.net