From the MSDN : StringBuilder(int,int)
Initializes a new instance of the StringBuilder class that starts with a specified capacity and can grow to a specified maximum.
So the Capcity
is the size with which it has tobe started/created and MaxCapacity
is the Limitation of the Stringbuilder
.
Example 1: Try the following example one by one
StringBuilder str = new StringBuilder(3, 5);
str.Append("1"); //no error as Length 1 <= max limit 5
str.Append("12"); //no error as Length 2 <= max limit 5
str.Append("123"); //no error as Length 3 <= max limit 5
str.Append("1234"); //no error as Length 4 <= max limit 5
str.Append("12345"); //no error as Length 5 <= max limit 5
str.Append("123456"); //error as Length 6 is not <= max limit 5
Example 2: Try the following example all at once
StringBuilder str = new StringBuilder(3, 5);
str.Append("1"); //no error as str Length 1 <= max limit 5
str.Append("12"); //no error as str Length 3 <= max limit 5
str.Append("123"); //error as str Length 6 is not <= max limit 5
EDIT:
Yes MaxCapacity
is seldomly used.
StringBuilder(int Capacity) : with Capacity
parameter it creates the StringBuilder
object in memory.
as soon as user adds items and if the size exceeds its capacity limit then it allocates more memory to accomdate the exceeded characters and it keeps growing untill unless there is no problem with the memory.
StringBuilder(int Capacity,int maxCapacity) : it does the same as above one parameter Constructor but before creating/increasing its runtime memory to accomdate exceeded characters it checks for MAXCAPACITY
limit ,if it exceeds the MAXCAPACITY
limit then throws the Exception
.
From the below commnets : As @Sriram said MaxCapacity
parameter has nothing to do with memory allocation.