Tuesday, August 4, 2009

C# Verbatim String Literals - No Escape : )

Alright, so I'll admit to having been a VB for most of my career because I just find it more intuitive. Recently, though, I have been expanding my horizons and "c#-pening" my .Net skills. Tonight I cam across a really cool C# feature called verbatim string literals. Instead of having to escape certain special characters in a string literal such as in a file path:

string path = "c:\\c#.net\\file

You can simply prefix your literal with an @ symbol and everything between the quotes is taken literally by the c# compiler

string path = @"c:\c#.net\files";

The one caveat is that to use quotes around a character in a verbatim string literal you have to code the literal with double quotes like:

string msg = @"Type ""x"" to exit";

So, you do have to escape some characters but whattya want?

BTW - the examples were taken from Murach's C# 2008. I don't even know the guy but Mike Murach has taught me abotu 3 different programming languages (including SQL Server that isn't really a programming language, technically).

No comments:

Post a Comment