Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping verbatim string literals

I have the following string which won't compile:

String formLookupPull = @"SELECT value1, '"+tableName+"', '"+columnName+"' FROM lkpLookups WHERE ""table"" = '" + tableName + "' and ""field"" = '" + columnName + "';";

The offending sections are :

""table"" =

and

""field"" = 

The compiler is getting all mixed up on the escape sequence. Can anyone see what's wrong?

like image 793
Brian Sweeney Avatar asked Mar 16 '09 22:03

Brian Sweeney


2 Answers

To address your title question...

To escape the quote in a verbatim string literal, use the quote-escape-sequence "" (that's two quote characters)

string a = @"He said ""Hi!""..."; // He said "Hi!"...

See MSDN for more details on escaping, etc.

Note that in your posted code, the only verbatim string is the very first one (with the @ before it). The subsequent strings are not verbatim, so the proper escape sequence would be \".

You can make it look prettier with string.Format:

String formLookupPull = 
   string.Format(@"SELECT value1, '{0}', '{1}' FROM lkpLookups" +
                 @"WHERE ""table"" = '{0}' and ""field"" = '{1}';", 
                 tableName, columnName)
like image 95
Daniel LeCheminant Avatar answered Oct 12 '22 20:10

Daniel LeCheminant


The problem is that not all the strings you are concatenating are verbatim string literals, only the first portion of the concatenation is.

In other words,

@"SELECT value1, '"

is the only verbatim literal in the entire statement to build the final string.

You would need to add @ in front of the rest of your strings to make them all verbatim.

Which would make it look like:

String formLookupPull = @"SELECT value1, '"+tableName+ @"', '"+columnName+ @"' FROM lkpLookups WHERE ""table"" = '" + tableName + @"' and ""field"" = '" + columnName + @"';";
like image 34
Quintin Robinson Avatar answered Oct 12 '22 20:10

Quintin Robinson