tags:

views:

122

answers:

4

The first line is true, the second is false. htmlOut and s2 are StringWriter objects.

    bool b = s2.ToString() == htmlOut.ToString();
    ret = htmlOut.Equals(s2);

I expected true which b is but why is ret false?

+2  A: 

The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Does the type of htmlOut have a non-default overridden Equals method?

In this case, it seems not, and it's telling you that they are different instances, whether or not their semantic values match up.

Steve Gilham
+8  A: 

StringWriter uses an internal StringBuilder to write to. StringWriter.ToString() returns the string built by StringBuilder.

StringWriter does not override object.Equals() so StringWriter.Equals() compares if the two objects are the same reference, not if their string representations are equal.

dtb
so with StringWriter .Equals is the same as == ?
acidzombie24
`StringWriter` does not implement the `==` operator which defaults to reference equality, too, so yes.
dtb
+1  A: 
htmlOut.ToString().Equals(s2.ToString());

this will return true

ArsenMkrt
+3  A: 

StringWriter doesn't override object.Equals.

htmlOut.Equals(s2);

is equivalent to :

object.ReferenceEquals(htmlOut, s2);
CMS
Not exactly. `htmlOut.Equals(s2);` will throw a `NullReferenceException` if `htmlOut` is `null` while `object.ReferenceEquals(htmlOut, s2);` will not.
dtb