Search code examples
c#unit-testingtostringstringbuilderimplicit-conversion

What is the difference between implicit and explicit StringBuilder.ToString() method calls?


I just wrote a small Unit Test in which I used a StringBuilder().

var stringBuilder = new StringBuilder();
stringBuilder.Append("Foo");

Assert.AreEqual(stringBuilder, "Foo");

This Test will fail.

Expected: <Foo>
But was:  "Foo"

But if I change the Assert to

Assert.AreEqual(stringBuilder.ToString(), "Foo");

the test will pass.

So, what is the difference between the implicit call and the explicit call of the ToString() method? Or/And what are these Brackets (<>) standing for?


Solution

  • In your first example, you are testing if your StringBuilder instance is equal to the string, which will fail.

    In your second one, you are testing if the result of the call to ToString() (which is a string) is equal to the other string.


    The bracktes (<>) are NUnits way to indicate that it got an non-string object, but to display the message, NUnit calls ToString() on that object.

    Expected: <Foo> But was: "Foo"
    

    So <Foo> is an object that returns Foo on a call to ToString(), whereas "Foo" is just a String Foo.

    MSTest would show you a different message, which would be more clear:

    Expected:<Foo (System.Text.StringBuilder)>. Actual:<Foo (System.String)>.