What is capacity and length for StringBuilder ?

 Posted by Bhakti on 12/14/2009 | Category: ASP.NET Interview questions | Views: 8957

By specifying capacity you can indicate number of characters the instance object of stringbuilder can hold while the length is the character count of the string the stringbuilder holds.
Specifying lesser capacity and longer string will make capacity to get expanded to accommodate the supplied string. But specifying higher capacity and lesser length will shorten the string content.
Unless specified, the default capacity of the stringbuilder is 16.

    Dim sb As New StringBuilder("Hi", 5) ' initial capacity is set to 5

Response.Write(sb.Capacity) ' will print 5
Response.Write(sb.Length) ' will print 2
sb.Append(" testing")
Response.Write(sb.Capacity) ' will print 10
Response.Write(sb.Length) ' will print 10
sb.Length = 5
Response.Write(sb) ' will print hi te

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response