Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to define multiline String Literal in C#?
A multiline string literal in C# allows you to define strings that span multiple lines while preserving the line breaks and formatting. This is achieved using the @ symbol prefix, which creates a verbatim string literal.
Syntax
Following is the syntax for defining a multiline string literal −
string variableName = @"Line 1 Line 2 Line 3";
The @ symbol tells the compiler to treat the string literally, preserving all whitespace, line breaks, and special characters without requiring escape sequences.
Using Verbatim String Literals
Let's say you want to create a string with the following content −
Welcome User, Kindly wait for the image to load
For a multiline string literal, you can define it using the @ prefix −
string str = @"Welcome User, Kindly wait for the image to load";
Example
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
string str = @"Welcome User,
Kindly wait for the image to
load";
Console.WriteLine(str);
}
}
}
The output of the above code is −
Welcome User, Kindly wait for the image to load
Using Multiline Strings for File Paths
Multiline strings are particularly useful for file paths and SQL queries where you want to avoid escape sequences −
Example
using System;
class Program {
static void Main() {
string filePath = @"C:\Users\Documents\MyFolder\file.txt";
string sqlQuery = @"SELECT Name, Age
FROM Students
WHERE Age > 18";
Console.WriteLine("File Path: " + filePath);
Console.WriteLine("\nSQL Query:");
Console.WriteLine(sqlQuery);
}
}
The output of the above code is −
File Path: C:\Users\Documents\MyFolder\file.txt SQL Query: SELECT Name, Age FROM Students WHERE Age > 18
Escaping Double Quotes in Verbatim Strings
To include double quotes within a verbatim string, use two consecutive double quotes "" −
Example
using System;
class Program {
static void Main() {
string message = @"She said, ""Hello, World!""
and then smiled.";
Console.WriteLine(message);
}
}
The output of the above code is −
She said, "Hello, World!" and then smiled.
Conclusion
Multiline string literals in C# using the @ prefix provide a convenient way to define strings spanning multiple lines while preserving formatting. They eliminate the need for escape sequences and are particularly useful for file paths, SQL queries, and formatted text output.
