Thursday, February 2, 2012

The C# @ String Literal

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 as a language seems to be more notorious for having hundreds of lines of String.Append()s. 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.
I'd say the most precious and special super power of a string literal is its multi-line ability. So instead of writing 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.

No comments:

Post a Comment