473,806 Members | 2,754 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# strings

I have a couple of questions regarding C# strings.

1) Sometimes I see a string in someone else's code like:

string foo = @"bar";

What does the '@' do for you?
2) Is there a performance loss if I start concatenating strings together
with the + operator ? In Java, they discouraged code like this:

string command = "CMD " + var1 + " " + var2;

The reason is because of all of the temporary String objects that get
created in the meantime. The solution is to use a StringBuffer like so:

StringBuffer command = new StringBuffer("C MD ");
command.append( var1);
command.append( ' ');
command.append( var2);
System.out.prin tln(command.toS tring());

This is less expensive than the above code because String objects are not
being created left & right. Does C# have the same problem? I noticed that
C# has a StringBuilder class which is just like the Java StringBuffer class.
Should I use StringBuffer in cases like the above where I need to
concatenate multiple strings to one string?
Nov 15 '05 #1
20 2399
Hi Trevor,

Please see response in-line.

Joe
--
http://www.csharp-station.com

"Trevor" <tr****@nospam. com> wrote in message
news:uC******** ******@TK2MSFTN GP12.phx.gbl...
1) Sometimes I see a string in someone else's code like:

string foo = @"bar";

What does the '@' do for you?
That's a verbatim string literal, which preserves characters between the
double quotes. One of its uses is when you want to make file paths more
readable. For example, in a normal string, you would escape the path
separator like this:

"c:\\MyDir\\MyS ubDir\\MyFile.c s"

Instead, you can do this:

@"c:\MyDir\MySu bDir\MyFile.cs"

Also, you can sometimes do something like this:

@"
This is some text that I
want to show on the
console with line feeds
"
Instead of:

"This is some text that I\n want to show on the\n console with line feeds"

or something else less readable.
2) Is there a performance loss if I start concatenating strings together
with the + operator ? In Java, they discouraged code like this:

string command = "CMD " + var1 + " " + var2;

Yes, there is a performance penalty with these concatenations because of new
string objects being created on each concatenation. The string type is
immutable.
Should I use StringBuffer in cases like the above where I need to
concatenate multiple strings to one string?


You should use the StringBuilder. I use a rule-of-thumb that when I have 4
or more concatenations, I will use a StringBuilder instead.
Nov 15 '05 #2

"Trevor" <tr****@nospam. com> wrote in message
news:uC******** ******@TK2MSFTN GP12.phx.gbl...
I have a couple of questions regarding C# strings.

1) Sometimes I see a string in someone else's code like:

string foo = @"bar";

What does the '@' do for you?
2) Is there a performance loss if I start concatenating strings together
with the + operator ? In Java, they discouraged code like this:

string command = "CMD " + var1 + " " + var2;


Hello Trevor,

#2: C# is much the same, and the string builder class is provided for that.
I think though that if you are just concatenating a couple of variables, the
performance hit isn't so hard. It's building large strings where string
builder is handy. There's been lots of discussion on this topic, but for
myself, I use string builder if I'm concatenating more than say 10 items.

#1: The @ sign causes the compiler to treat the string as it is, and not
look for escape characters and whatnot, or something like that. I only know
that if I want to hardcode a folder and filename, or something like that, I
have to use the @"[string]" or it doesn't work properly. Surely someone else
will give a more definitive answer. Looking forward to that myself.

Eric
Nov 15 '05 #3
Trevor,

See inline.

"Trevor" <tr****@nospam. com> wrote in message
news:uC******** ******@TK2MSFTN GP12.phx.gbl...
I have a couple of questions regarding C# strings.

1) Sometimes I see a string in someone else's code like:

string foo = @"bar";

What does the '@' do for you?
The amperstand means to take the string as a literal, and not interpret
escape codes. For example, when working with paths, you have to use "\"
twice for each path separator, because "\" needs to be escaped, like so:

"c:\\temp"

However, with a string literal, there are no escape characters, so you
don't have to worry. You can write this:

@"c:\temp"


2) Is there a performance loss if I start concatenating strings together
with the + operator ? In Java, they discouraged code like this:

string command = "CMD " + var1 + " " + var2;

The reason is because of all of the temporary String objects that get
created in the meantime. The solution is to use a StringBuffer like so:

StringBuffer command = new StringBuffer("C MD ");
command.append( var1);
command.append( ' ');
command.append( var2);
System.out.prin tln(command.toS tring());

This is less expensive than the above code because String objects are not
being created left & right. Does C# have the same problem? I noticed that C# has a StringBuilder class which is just like the Java StringBuffer class. Should I use StringBuffer in cases like the above where I need to
concatenate multiple strings to one string?
Generally speaking, if you have a lot of string manipulation to do, then
you should use a StringBuilder instance to do it. It will be faster than
just concatenating strings. It should be noted that the following line:

string command = "CMD " + var1 + " " + var2;

Is actually going to be compiled into:

string command = String.Concat(" CMD ", var1, " ", var2);

Underneath the covers, Concat uses a StringBuilder instance to do its
work. Also, it should be noted that the compiler treats the concatenation
of two string literals as a single instance. In other words:

"Hello " + "there"

Is compiled into:

"Hello there"

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

Nov 15 '05 #4
"Trevor" <tr****@nospam. com> writes:
1) Sometimes I see a string in someone else's code like:

string foo = @"bar";

What does the '@' do for you?
In that case it does nothing, the @ symbol stands for
"treat the string as a raw string and don't escape nothing"

So if you are (for example) using a string to store a path
you can do that in the two following ways:

string path = "c:\\windows\\s ystem32"

or

string path = @"c:\windows\sy stem32"

You gain the same behavior with other escape chars (\n, \t and so on)
2) Is there a performance loss if I start concatenating strings together
with the + operator ? In Java, they discouraged code like this:

string command = "CMD " + var1 + " " + var2;

The reason is because of all of the temporary String objects that get
created in the meantime. The solution is to use a StringBuffer like so:

StringBuffer command = new StringBuffer("C MD ");
command.append( var1);
command.append( ' ');
command.append( var2);
System.out.prin tln(command.toS tring());


Yeah, in .NET is pretty the same thing. It's discouraged to concatenate
strings cause they are "immutable" (a Python definition) and every
"string1" + "string2" generates a new instance (AFAIK). So .NET put in
place a class called StringBuilder (used in the same way as the
StringBufffer above) in the System.Text namespace

example:

using System.Text;

..... blah blah...

StringBuilder command = new StringBuilder(" CMD ");
command.Append( var1);
command.Append( " ");
command.Append( var2);
Console.WriteLi ne(command.ToSt ring());
--
Lawrence "Rhymes" Oluyede
http://loluyede.blogspot.com
Nov 15 '05 #5
@ says "This is my string, including any special characters". In other
cases, you have to include special characters. For example, to have the
string "10\10" you would write either as "10\\10" or @"10\10".

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

*************** *************** *************** *************** **********
Think Outside the Box!
*************** *************** *************** *************** **********
"Trevor" <tr****@nospam. com> wrote in message
news:uC******** ******@TK2MSFTN GP12.phx.gbl...
I have a couple of questions regarding C# strings.

1) Sometimes I see a string in someone else's code like:

string foo = @"bar";

What does the '@' do for you?
2) Is there a performance loss if I start concatenating strings together
with the + operator ? In Java, they discouraged code like this:

string command = "CMD " + var1 + " " + var2;

The reason is because of all of the temporary String objects that get
created in the meantime. The solution is to use a StringBuffer like so:

StringBuffer command = new StringBuffer("C MD ");
command.append( var1);
command.append( ' ');
command.append( var2);
System.out.prin tln(command.toS tring());

This is less expensive than the above code because String objects are not
being created left & right. Does C# have the same problem? I noticed that C# has a StringBuilder class which is just like the Java StringBuffer class. Should I use StringBuffer in cases like the above where I need to
concatenate multiple strings to one string?

Nov 15 '05 #6
StringBuilder is more efficient when firing off a lot of manipulation.

Inefficient
----------
string x = "something" ;
x += "Something else";
x += "Something else";
x += "Something else";
x += "Something else";
x += "Something else";

It would be better to use StringBuilder here.

string x = "something" + var1 + "something else" + var2;

Not a big issue here, as the end string is not being manipulated over and
over again (creating a new string each time). If you are simply concating,
adding to a string is fine. The benefit of the StringBuilder is cleaner
code, but more typing, especially when concating 100s of variables.
--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

*************** *************** *************** *************** **********
Think Outside the Box!
*************** *************** *************** *************** **********
"Trevor" <tr****@nospam. com> wrote in message
news:uC******** ******@TK2MSFTN GP12.phx.gbl...
I have a couple of questions regarding C# strings.

1) Sometimes I see a string in someone else's code like:

string foo = @"bar";

What does the '@' do for you?
2) Is there a performance loss if I start concatenating strings together
with the + operator ? In Java, they discouraged code like this:

string command = "CMD " + var1 + " " + var2;

The reason is because of all of the temporary String objects that get
created in the meantime. The solution is to use a StringBuffer like so:

StringBuffer command = new StringBuffer("C MD ");
command.append( var1);
command.append( ' ');
command.append( var2);
System.out.prin tln(command.toS tring());

This is less expensive than the above code because String objects are not
being created left & right. Does C# have the same problem? I noticed that C# has a StringBuilder class which is just like the Java StringBuffer class. Should I use StringBuffer in cases like the above where I need to
concatenate multiple strings to one string?

Nov 15 '05 #7
Hi,

Answers inline...

Regards,
Madhu

MVP | MCSD.NET
-----Original Message-----
I have a couple of questions regarding C# strings.

1) Sometimes I see a string in someone else's code like:

string foo = @"bar";

What does the '@' do for you?
All the escape sequence are not processed if you have
the '@' character. thus making things very simple.
for example: if you want the string to have the value
c:\docs\sample. txt, you can write it in two ways,
string foo = "c:\\docs\\samp le.txt";
or
string foo = @"c:\docs\sampl e.txt";
2) Is there a performance loss if I start concatenating strings togetherwith the + operator ? In Java, they discouraged code like this:
string command = "CMD " + var1 + " " + var2;

The reason is because of all of the temporary String objects that getcreated in the meantime. The solution is to use a StringBuffer like so:
StringBuffer command = new StringBuffer("C MD ");
command.append (var1);
command.append (' ');
command.append (var2);
System.out.pri ntln(command.to String());

This is less expensive than the above code because String objects are notbeing created left & right. Does C# have the same problem? I noticed thatC# has a StringBuilder class which is just like the Java StringBuffer class.Should I use StringBuffer in cases like the above where I need toconcatenate multiple strings to one string?

You are right!!! because in both the cases String is
immutable and thus creates lot of string objects.
Nov 15 '05 #8
Trevor <tr****@nospam. com> wrote:
I have a couple of questions regarding C# strings.

1) Sometimes I see a string in someone else's code like:

string foo = @"bar";

What does the '@' do for you?
It makes it a "verbatim string literal" which means you don't have to
escape backslashes and the like.
2) Is there a performance loss if I start concatenating strings together
with the + operator ? In Java, they discouraged code like this:

string command = "CMD " + var1 + " " + var2;

The reason is because of all of the temporary String objects that get
created in the meantime. The solution is to use a StringBuffer like so:

StringBuffer command = new StringBuffer("C MD ");
command.append( var1);
command.append( ' ');
command.append( var2);
System.out.prin tln(command.toS tring());

This is less expensive than the above code because String objects are not
being created left & right.


It's really *not* any less expensive. Please read
http://www.pobox.com/~skeet/java/stringbuffer.html for more
information.

..NET's StringBuilder is indeed very similar to Java's StringBuffer, and
is useful in exactly the same circumstances - which doesn't include the
above.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #9
Joe Mayo <jm***@nospamAt CSharpDashStati on.com> wrote:
Please see response in-line.
[Please fix your posting style so your response doesn't end up below
your sig separator, otherwise clients which automatically strip sigs
end up having problems quoting your post.]
string command = "CMD " + var1 + " " + var2;

Yes, there is a performance penalty with these concatenations because
of new string objects being created on each concatenation. The string
type is immutable.


No, there's no performance penalty above. Only a single string is being
created, as the above gets turned into

string command = String.Concat ("CMD ", var1, " ", var2);

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
5782
by: Ravi | last post by:
Hi, I have about 200GB of data that I need to go through and extract the common first part of a line. Something like this. >>>a = "abcdefghijklmnopqrstuvwxyz" >>>b = "abcdefghijklmnopBHLHT" >>>c = extract(a,b) >>>print c "abcdefghijklmnop"
17
7405
by: Gordon Airport | last post by:
Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently interchangeable in all circumstances (as long as they're paired) so there's no overloading to muddy the language. Of course there could be some interesting problems with current code that doesn't make a distinction, but it would be dead easy to fix...
2
22615
by: Potiuper | last post by:
Question: Is it possible to use a char pointer array ( char *<name> ) to read an array of strings from a file in C? Given: code is written in ANSI C; I know the exact nature of the strings to be read (the file will be written by only this program); file can be either in text or binary (preferably binary as the files may be read repeatedly); the amount and size of strings in the array won't be known until run time (in the example I have it in...
19
3118
by: pkirk25 | last post by:
I wonder if anyone has time to write a small example program based on this data or to critique my own effort? A file called Realm List.html contains the following data: Bladefist-Horde Nordrassil-Horde Draenor-Alliance Nordrassil-Alliance Nordrassil-Neutral Draenor-Horde
95
5448
by: hstagni | last post by:
Where can I find a library to created text-based windows applications? Im looking for a library that can make windows and buttons inside console.. Many old apps were make like this, i guess ____________________________________ | | | ------------------ | | | BUTTON | | | ...
0
9599
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10371
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10374
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9193
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7650
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6877
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5546
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3853
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3010
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.