I know C# quite well and thought I knew all the language features, both old, new, and forthcoming. Today I was completely surprised when I discovered a feature that has existed since C# 1.0 that I never knew about… String literals in C# can span multiple source lines!

My voyage to discovery started when reading a post by Oren Eini about an unrelated subject. He casually mentioned his annoyance that Microsoft used string concatenation in its examples and why weren’t they using multi-line strings. Oren is a smart guy and generally knows what he’s talking about. So I started poking around. The following code results in a compiler error, as I expected:

string sql = "SELECT foo
              FROM bar
              WHERE baz=42";

So regular strings cannot span multiple lines, which is why you commonly see it written as:

string sql = "SELECT foo " + 
             "FROM bar " +
             "WHERE baz=42";

I can wax poetic all day about the advantages/disadvantages of hard-coded SQL in your code. The reality is that if you’re not using an object-relational mapper (such as NHibernate – and you really should be), you need to stick the SQL somewhere. Code is as good a place as any. The truly awful part is round-tripping the SQL between a query editor and C# for tuning or investigation purposes because you have to strip out all those double-quotes and plus signs. But C# has another type of string — the string literal (@””). As it turns out, string literals can span multiple lines. The following is completely valid C# and even provides decent readability of the SQL in your C# code:

string sql = @"SELECT foo
               FROM bar
               WHERE baz=42";

Maybe LINQ (in .NET 3.5) will do away with the need for SQL in quoted strings, but until that day, my SQL statements became a little bit more wieldy.