简体   繁体   中英

C# How StringBuilder is mutable?

I was trying to find out a post which should explain how exactly append function works for StringBuilder.

I got across through this answer.

Now, String is immutable. I get this.

But, StringBuilder is also initializing a new temporary character array whenever we try to append something to it.

Mutable doesn't mean that it can't create new stuff. Mutable just means that its state can change after the constructor returns.

For example, this is mutable, even though string is immutable:

class Foo {
    public string Bar { get; set; }

    public void FooMethod() {
        Bar = new string('!', 10);
    }
}

Because we can change the state of it by setting Bar or calling FooMethod :

 someFoo.FooMethod();

Yes, I am creating a new string here in the FooMethod , but that does not matter. What does matter is that Bar now has a new value! The state of someFoo changed.

We say StringBuilder is mutable because its state can change, without creating a new StringBuilder . As you have looked up, StringBuilder stores a char array. Each time you append something, that char array changes to something else, but no new StringBuilder s are created. This is solid proof that StringBuilder is mutable.

The *Builder pattern is a common pattern for creating objects, especially immutable objects, using a richer interface than simply passing in a bunch of data in the constructor. The relation between class X and a class XBuilder will usually be an immutable X and an XBuilder that can build an X. XBuilder doesn't need to be immutable, because it's not the actual data type you eventually need, it's just a temporary scaffold for constructing X .

In other words, StringBuilder isn't a mutable version of string . It's a class, a unit of functionality, that exists to help you create an immutable string . You instantiate a StringBuilder , use its various Append methods to define what should be in the final string (which doesn't, logically, exist yet), and then, when you're done, call myStringBuilder.ToString() (which, I think, should have been called BuildString() ), to get the actual string you wanted.

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