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
*/
AlanPosted Aug 23, 2008, 6:40 PM
buffer[i] is the char and output is the string. buffer[i] is the indexer for the StringBuilder, buffer, and, like the indexer for a string, returns the char at index i.
Curiously, there's no implicit or explicit conversion from char to string even though a string is really a sequence of chars. So, this doesn't work as it stands:
output = buffer[i];
To make it work you have to do this:
output = buffer[i].ToString();
However, addition between strings and chars is defined - in effect, the char is converted to a string and then concatenated with the string. So, this does work:
output += buffer[i];
Posted Aug 23, 2008, 7:32 PM
Thank you very much for explanation.