Friday, April 3, 2009

Verbatim Literal Strings

I am filing this one under “you learn something new every day”. This is a little feature of the C# language that I only recently learned about.

As you probably know when you put literal strings in a C# program certain character sequences are interpreted as escape characters.  For example if you do this:

it will output

line1
line2

because \n is interpreted as a newline. What if we actually wanted the characters \n to be displayed? You could do this:

This works fine for simple short strings, but starts to get a little ugly in more complex strings especially when you are dealing with regular expressions or URLs.  Here is an alternative syntax that does the same thing:

The ‘@’ character tells the compiler to take the string verbatim and not to interpret any escape sequences. This syntax also allows you to do things like this:

If you didn’t use a verbatim string definition here this would cause a syntax error. In this case since it will actually each piece of text on a different line.

1 comment:

Anonymous said...

Hello. And Bye.