But be sure to think code readability, as well. For example, this is a lot
more readable:
string name = lastname + ", " + firstname;
then the following
StringBuilder nameBuilder = new StringBuilder();
nameBuilder.Append (lastname);
nameBuilder.Append (", ");
nameBuilder.Append (firstname);
string name = nameBuilder.ToString();
Not to mention that the first is quicker to write and less error prone, and
quite possibly faster in execution.
I would even suggest that if you're concatenating 100,000 names, still only
use the string builder to put all the names together, something like:
StringBuilder nameBuilder = new StringBuilder();
foreach (DataRow row in myDataTable)
{
nameBuilder.Append (row[lastname] + ", " + row[firstname] +
Environment.NewLine);
}
instead of:
StringBuilder nameBuilder = new StringBuilder();
foreach (DataRow row in myDataTable)
{
nameBuilder.Append (row[lastname]);
nameBuilder.Append (", ");
nameBuilder.Append (row[firstname]);
nameBuilder.Append (Environment.NewLine);
}
I think this simplistic case would be fairly readable written either way,
but the first example keeps the name grouped together nicely, so if you add
an address, and other stuff, you don't need to split it all out with
comments:
//Add name
four
lines
to build
name
// Add Address
eight
lines of
code to
assemble
an address
from street, city state, etc
and on.
--
Mike Mayer
http://www.mag37.com/csharp/
(e-mail address removed)
Alvin Bruney said:
well for starters, i got this kind of construct peppered all over my
code.
i
start off with good intentions with the append but there seems to always be
a piece of string needing to be added and not worth the starting a new line.
i know that is so lazy. always figured the language was smart enough to know
better.
i didn't care to read spec 14.15. what does it say in the queens
english?
do
i need to stop doing that (is really what i am asking)
StringBuilder
when wrote
in what