Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Line in Constant error

I am writing a c# code in which i am fetching values from the database and using it. The problem i am facing is as below.

If my fetched value from the database is :

 string cat1 = "sotheby's"; 

now while using this cat i want to insert an escape character before single quote, to achieve this i have written the below code:

  string cat1 = "sotheby's";                     if (cat1.Contains("'")) {                         var indexofquote = cat1.IndexOf("'");                         cat1.Insert(indexofquote-1,"\");                         var cat2 = cat1;                     } 

The error rises in insert line, the backslash(escape character). The error is New Line in Constant. Please help me how to correct this error.

like image 385
Furquan Khan Avatar asked Jul 19 '13 06:07

Furquan Khan


People also ask

What is newline in constant error in C#?

The "Newline in constant" error usually means that somewhere in the code you start a string by opening quotes and then fail to close the quotes.

How do I add a new line in interpolation?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

What is the newline character in C?

The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen.


2 Answers

You can't just write "\" in C# code. That will produce the "New Line in Constant" error because it 'escapes' the second quote so that it doesn't count. And the string isn't closed.

Use either "\\" (escaping the \ with itself)
or use @"\" (a verbatim string).

like image 199
Henk Holterman Avatar answered Sep 20 '22 07:09

Henk Holterman


The Backslash in string literals is an escape character, so it must either be escaped itself:

"\\" 

Or you can use a so-called verbatim string literal:

@"\" 

See: http://msdn.microsoft.com/en-us/library/aa691090.aspx

Regarding your compile error: The backslash escapes the following quotation mark, thus the string literal is not recognized as closed. The following characters ) and ; are valid for string literals, however the line ending (newline) is not. Hence the error.

like image 36
nodots Avatar answered Sep 24 '22 07:09

nodots