简体   繁体   中英

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?

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)>.   

In the first version there is no implicit call to ToString This only happens in methods like Console.WriteLine.

So what actually happens is that you are equating a stringbuilder object to a string object. Even the types do not match :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM