String literals in C#

25 December, 2009 | | 2 comments |

Share |
I'm sure a quick peek at the subject of this blog post might make C# enthusiasts think of a mundane topic with nothing to offer. But contrary to that, it has much more to enlighten you. So just read on ...

Strings in C#

Lets clear some of the dare-bare basics regarding Strings(which we thought we knew) in C# :

Strings are reference types used to contain Unicode text.

C# supports two forms of string literals :

1] Regular string literals

A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as '\t' for the tab character) and hexadecimal and Unicode escape sequences. This is the most general form of String which we all use everyday in our work.

Some examples :

String s;


--> s = "This is String";

O/P : This is String


--> s = "Hello \t world";

O/P : Hello world


--> s = "My name is \"Hardik " + "Shah\"";

O/P : My name is "Hardik Shah"


As noticed above the following backslash character constants are used frequently while getting a particular O/P in your required format :

| \n | \t | \v | \b | \f | \\ | \" | \' |

Also if you have a large string than you have to append string parts using the '+' operator.

To win over this situation, we have another type of String literal i.e. Verbatim string literals.

2] Verbatim string literals
A verbatim string literal consists of an '@' character followed by a double-quote character, zero or more characters, and a closing double-quote character. So here we have the added advantage that the characters present between the two double-quotes are rendered the way they are and no white-spaces are truncated. Also a lot more ....

Some examples :

String s;


--> s = @"hello world";

O/P : hello world


s = @"Division is (a\b)";

O/P : Division is (a\b)


--> s = @"append this type " + @"in this way";

O/P : append this type in this way


Note : ["] in Verbatim string literal is [""] or [\""]

Applications of verbatim string literals :

1] Include a large paragraph of text without using '+' operator.

2] Multiple lines of HTML code can also be used using this type.

Post a Comment


Joel said...

arre yaar this turned out to be a mundane topic only!

simi said...


First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

There is a good C# resource site, Have alook