0

I have a string like this

'Name.ToLower().Contains ("") And Created < ("05/12/2022 01:41:16") And Disabled == false'

How to deal with this in C#?

I've tried prepending with @""" etc.

dotnet fiddle

phuclv
  • 37,963
  • 15
  • 156
  • 475
fuzzybear
  • 2,325
  • 3
  • 23
  • 45
  • 1
    I believe the multiple quotes thing is a C# 11 preview, so unless you're explicitly using C# 11 for your code, I don't think it will work. – ProgrammingLlama May 12 '22 at 02:23
  • I can use c# 11 that no prob's infact i'm doing that right now :) – fuzzybear May 12 '22 at 02:24
  • Does this answer your question? [Escape double quotes in a C# string](https://stackoverflow.com/questions/26115253/escape-double-quotes-in-a-c-sharp-string) – Charlieface May 12 '22 at 09:16

3 Answers3

1
var a = @"'Name.ToLower().Contains ("""") And Created < (""05/12/2022"") And ExpandOnStart == false'";

like this?

Matti Price
  • 3,351
  • 15
  • 28
0

Obviously you have to escape special characters somehow. In older C# use verbatim strings: https://dotnetfiddle.net/8OtiKP

@"'Name.ToLower().Contains ("""") And Created < (""05/12/2022"") And ExpandOnStart == false'"

As you can see, " still needs to be escaped with "", but all the other characters, including \ can be left as-is

In C#11 there's a better solution: raw string literal where there's no need to escape " at all

"""'Name.ToLower().Contains ("") And Created < ("05/12/2022 01:41:16") And Disabled == false'"""
phuclv
  • 37,963
  • 15
  • 156
  • 475
0

This is a bit different approach, but you mentioned that the string is created by appending other strings, so possibly it'll help.

var createdDate = "05/12/2022";
var name = "some name";
var expandOnStart = "false";

var theString = $"Name.ToLower().Contains(\"{name}\") And Created < (\"{createdDate}\") And ExpandOnStart == \"{expandOnStart}\"";

// theString = Name.ToLower().Contains("some name") And Created < ("05/12/2022") And ExpandOnStart == "false"

https://dotnetfiddle.net/oq3UYq

DACrosby
  • 11,116
  • 3
  • 39
  • 51
  • Hi, thanks for that the string is orignally like this 'Name.ToLower().Contains ("") And Created < ("05/12/2022 01:41:16") And Disabled == false' so we need to put that into a var first ideally ? – fuzzybear May 12 '22 at 02:18
  • Where are you getting the string from? Possibly pasting it into C# directly is not the best solution - e.g. if it's in a csv, might be better to read from the file and programmatically avoid quote escaping when you read the input – DACrosby May 12 '22 at 02:33