Hi there,

I've been reading a book on c# and come across a method that is EnsureCapacity on StringBuilder which from understanding it makes sure that how much capacity a variable can hold.

What I made is a variable and then tested it.

StringBuilder st = new StringBuilder("string builder"); // the length == 14


When I call the EnsureCapacity on this variable,it gives me 16. However, it gives me the exact length of the variable if and only if I explicitly specify the maxCap when initialise my variable like so.



new StringBuilder("string builder", 14);  14 or less

thanks..

Was there a question there? StringBuilider allocates space based on how it percieves what it will need. This makes it more effecient for appending strings to it (vs using String which has to allocate new memory every time you add something to it).

If you're cursious, the implementation for that StringBuilder constructor is (in Microsoft's .NET 4.0 implementation):

public StringBuilder(string value) : this(value, 16)
{
}

Which basically means, that if you don't specify a capacity it will be 16 or the length of the string, whichever is greater (I should also note that you should never rely on that always being true, as it could be implemented differently elsewhere).

And just to clarify, you should use the Capacity property if you just want to check the capacity. EnsureCapacity() should be used when you are going to be appending/inserting characters multiple times, and have an idea about how much total capacity you will need.

@Memorath.. the question wasnt stated directly. Yes, it is that why doesnt the ensure capacity method give the exact number of characters that I had in my string as shown in the code snippet I posted in the earlier post?

thank you..

@ nmaillet.. thanks for the explanation. Although, does the MaxCap stay 16? I mean is it by default?

No, the capacity changes as the string gets longer. Each time it is going to exceed the Capacity, it doubles in size. So it goes from 16 to 32, 64, 128,256, etc. Don't confuse Capacity with MaxCapacity (which is 2,147,483,647).

I think I will have to play around with those methods and see the difference. But thanks for that. I will put another reply in here after I give them a go!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.