The C# @ String Literal
Posted by: Brendan Kowitzs Web Log - Yes means I understand, however, it does not correspond to action.,
on 06 Mar 2007 |
View original | Bookmarked: 0 time(s)
C# is a pretty sweet language, and there are many, many, many little things that just make the code that much nicer. Have you ever been in a situation where for some reason you NEEDED to have a string/code fragment/js fragment/sql statement inline in your code because you don't believe in resource files or stored procedures?
Aside from whatever great debate about "if you should or shouldn't". If you are going to, please, please, learn to take advantage of what C# has to offer, yes I'm talking about the '@' string literal.
Now I'm not going to target anyone in particular, but my feeling is that VB programmers seem to be more notorious for hundreds of lines of String.Append()s then other programmers, but I could be wrong. String.Append is the absolute worst, hardest and most illegible way of possibly including your fragment inline in code.
There are also the programmers that 'know of' the @ symbol and prefix all their strings with it because it looks cool or something. Doing this without reason may actually alter the behaviour you excepted because it causes escape sequences to NOT be processed.
Eg. "c:\\my\\file.txt" could be done as @"c:\my\file.txt"
This means your \n and \t or whatever it is will also not be processed. Believe it or not by making your string a literal you can no longer use functions like String.Format(varLiteral, var1).
I'd say the most precious and special super power of a string literal is its multi-line ability. So instead of writing crap code that may look something like:
var1 += @"some text" + Environment.NewLine;
var1 += @"some more text" + Environment.NewLine;
var1 += @"even more text" + Environment.NewLine;
You could just use the @-quoting and write:
var1 = @"some text
some more text
event more text";
And yes that will compile perfectly fine. Best of all, even without going into the debate of "having inline fragments" at least I can read it and change it.