MorkaLork Development

Interesting stuff I've picked up over the years...

@ - Verbatim

2009-04-16 17:53:21 | 244 views | verbatim @ literal variables

The Basics



Sometimes you want to use keywords as variable names. Normally because you're an asshole and hate people, sometimes because you're just weird. However, if you feel an urge to do this, you can, by using the '@' sign before the variable name, like @if or @this. These are valid variable names and you should never use them.

More seriously though, the use of verbatim string literals tells the constructor to use the string literal that follows it "literally". This can be usefull if you are using escape characters or if you want to create a string that spans multiple lines.

Getting into it



There are two good ways to use the verbatim string literal method. There is also one bad, as mentioned above.

The bad way is to create keyword variables:



string @if = "Stupid variable";
string @for = "Horrible...";


The good way was to create strings containing escape characters like \ or to create multi-line strings.

Escape the escape chars


Here are two examples of how to create a string with a windows path:



string myDir = "C:\\Program\\stuff";
string myVerbDir = @"C:\Program\stuff";


Both these variables are correct. However, had we not but a '@'-sign before myVerbDir then we would've recieved this error:

Unrecognized escape sequence (CS1009)



Multiple lines in string


Here are examples on how to create multiline strings:



string myString = @"This string
spans over many lines
and that is quite cool,
isn't it?";

txtMain.Text = myString;


This will look like this:

imagehttp://morkalork.com/images/screenshots/verbatim1.jpg

That is how to create verbatim strings.






Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.