Blog Stats
  • Posts - 42
  • Articles - 0
  • Comments - 98
  • Trackbacks - 34

 

strObject1.Equals(strObject2) v/s strObject1 == strObject2

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.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Feedback

# re: strObject1.Equals(strObject2) v/s strObject1 == strObject2

Gravatar String literals are special. Try again with

string strObject3 = 'A'.ToString();

Don't forget to use object.ReferenceEquals to test for reference identity. 9/22/2005 9:05 PM | Raymond Chen

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

 

 

Copyright © Vinayak