6

In Ruby it's possible to use the strings without the need to escape the double quote in the string, like Q/Some my string with "double quotes"/

Is it possible with C# to use a string without a need to escape double quotes? For a good reason I need to write inline SQL and it's very annoying to escape double quotes every time I put SQL query from DB console to C# code.

I know it's possible to use \" or "" as one double quote. But is it possible to avoid the need to escape the double quotes?

Zelid
  • 6,905
  • 11
  • 52
  • 76
  • Simply put. No. You can use the @ symbol to stop "this is a "+ [newline for code clarity] "long string that you don't want on one line"; but there is no way to avoid the escape. – Paul Sullivan Aug 03 '12 at 08:21

3 Answers3

9

No, basically. You have the choice of "foo \" bar" or @"foo "" bar", both of which you have mentioned. However, frankly I rarely find " necessary in SQL; you have ' for literal strings and [ / ] for object/column names - of course, this might just be because I usually use SQL Server.

The only alternative that doesn't involve any escaping is to move the SQL to an external resource file, maybe a text file. That, though, is probably more painful than just using "".

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 3
    I use PostgreSQL, where CamelCase names should be escaped with double quotes. – Zelid Aug 03 '12 at 08:21
  • @Zelid yes, I suspected you might be using a different DB engine to me (I rarely see this issue). Sorry, you have to pick which option is least-worse, I guess. – Marc Gravell Aug 03 '12 at 08:22
5

No, this is not possible in C#. You could write your SQL in a separate file and then read it from there.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

For a good reason I need to write inline SQL and it's very annoying to escape double quotes every time I put SQL query from DB console to C# code.

If you are writing a Inline Sql Query you don't need to worry about quotes if you passed the values via SqlParameters. This way you won't see the annoying double quotes every where and even your query will safe from Sql Injection

HatSoft
  • 11,077
  • 3
  • 28
  • 43
  • I use Massive as lightweight DB access library. It always uses params escaping. I need to use double quotes in column and table names in PostgreSQL when I use CamelCase names. – Zelid Aug 03 '12 at 08:27
  • @Zelid oh in that case I agree it will be annoying seeing double quotes every where and I don't think you have another option – HatSoft Aug 03 '12 at 08:30
  • Yes I use EF Core and everything goes through that, and I have a `one off case` where its just easier to use SQL, (e.g. a report I've written) and seems a bit over kill to add a resource to project, read it in etc... just for that – Max Carroll Aug 05 '20 at 17:11