2
Answers

NP133 StringBuilder/EnsureCapacity()

Maha

Maha

16y
2.1k
1

Hi Guys

 

NP133 StringBuilder/EnsureCapacity()

 

In the following program if you remove + from code (highlighted in yellow)

that means if it is output = buffer[i]; output is producing error result. Error result is as follows.  

 

Cannot implicitly convert type 'char' to 'string'

 

I wish to know which is char and which is string?

 

Please explain.

 

Thank you

 

using System;

using System.Text;

 

class StringBuilderFeatures

{

    static void Main(string[] args)

    {

        StringBuilder buffer = new StringBuilder("Hello, how are you?");

 

        string output = "buffer = " + buffer.ToString() +

           "\nLength = " + buffer.Length +

           "\nCapacity = " + buffer.Capacity;

 

        buffer.EnsureCapacity(75);

 

        output += "\n\nNew capacity = " + buffer.Capacity;

 

        // truncate StringBuilder by setting Length property

        buffer.Length = 10;

 

        output += "\n\nNew length = " +

           buffer.Length + "\nbuffer = ";

 

        // use StringBuilder indexer

        for (int i = 0; i < buffer.Length; i++)

            output += buffer[i];

 

        Console.WriteLine(output);

    }

}

/*

buffer = Hello, how are you?

Length = 19

Capacity = 32

 

New capacity = 75

 

New length = 10

buffer = Hello, how

*/

Answers (2)