StringBuilder.Capacity Property is used to get or set the maximum number of characters that can be contained in the memory allocated by the current instance.
Syntax: public int Capacity { get; set; }
Return Value: This property will return the maximum number of characters that can be contained in the memory allocated by the current instance. Its value can range from Length to MaxCapacity.
Exception: This property will give ArgumentOutOfRangeException if the value specified for a set operation is less than the current length of this instance or the value specified for a set operation is greater than the maximum capacity.
Below programs will illustrate the use of the above-discussed property:
Example 1:
csharp
using System;
using System.Text;
class GFG {
public static void Main(String[] args)
{
StringBuilder str = new StringBuilder();
int cap = str.Capacity;
Console.WriteLine( "Default Capacity of StringBuilder = "
+ cap);
str.Append( "Geek" );
cap = str.Capacity;
Console.WriteLine( "StringBuilder = " + str);
Console.WriteLine( "Current Capacity of StringBuilder = "
+ cap);
}
}
|
Output:
Capacity of StringBuilder = 16
StringBuilder = Geek
Current Capacity of StringBuilder = 16
Example 2:
csharp
using System;
using System.Text;
class GFG {
public static void Main(String[] args)
{
StringBuilder str =
new StringBuilder( "WelcomeGeeks" );
int capacity = str.Capacity;
Console.WriteLine( "StringBuilder = " + str);
Console.WriteLine( "Capacity of StringBuilder = "
+ capacity);
}
}
|
Output:
StringBuilder = WelcomeGeeks
Capacity of StringBuilder = 16
Reference:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Sep, 2021
Like Article
Save Article