Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to set StringBuilder.Capacity when using P/Invoke?

Tags:

People also ask

What is the default capacity that is set to the StringBuilder?

Memory allocation The default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int32.

What is capacity in StringBuilder C#?

Default capacity of a String-Builder is 16 characters , And Max capacity of String-Builder is 2147483647 characters.

What is StringBuilder in C# with example?

C# StringBuilder is similar to Java StringBuilder. A String object is immutable, i.e. a String cannot be changed once created. Every time when you use any of the methods of the System. String class, then you create a new string object in memory.

How does StringBuilder work C#?

The StringBuilder works by maintaining a buffer of characters (Char) that will form the final string. Characters can be appended, removed and manipulated via the StringBuilder, with the modifications being reflected by updating the character buffer accordingly. An array is used for this character buffer.


Should StringBuilder.Capacity be set to the maximum number of .NET characters, without regards to null termination, or must it be set one higher to reserve space for a null terminator when using P/Invoke.

The natural reaction is that it should be set one higher, but it seems like P/Invoke is supposed to automatically compensate. In fact this is actually documented right here: http://msdn.microsoft.com/en-US/library/s9ts558h(v=VS.100).aspx

The reason for this question is that most examples are not strictly consistent with the above documentation. Almost always they are coded:

StringBuilder sb = new StringBuilder(dotNetChars + 1);
SomeWindowsAPI(sb, sb.Capacity);

Instead of:

StringBuilder sb = new StringBuilder(dotNetChars);
SomeWindowsAPI(sb, sb.Capacity + 1);

(I realize that some APIs handle the buffer size parameter differently. Assume that the API handles this the must common way, like GetFullPathName: http://msdn.microsoft.com/en-us/library/aa364963(v=VS.85).aspx)

Using an expression with sb.Capacity directly in the API call seems to be a best practice to avoid a mismatch. The issue is whether or not adding the +1 is correct.

Look around. You'll probably find that the only place showing sb.Capacity + 1 is the MSDN documentation.

Of course, one can allocate on the side of caution with a larger buffer than is strictly necessary, but I would like to know the consensus on how to do this.