.NET HELP

C# Multiline String (How it Works for Developers)

Updated May 24, 2023
Share:

What is a Multiline String?

In C#, a multiline string is a string that spans multiple lines. It's different from a single line string, which only consists of characters on one line. A multiline string in C# is created using string literals, which are a series of characters enclosed in double quotes. To form multiline strings, we need to use a special type of string literals called verbatim string literals.

The Magic of Verbatim Strings

To create a multiline string literal in C#, we use verbatim strings. Verbatim strings are prefixed with the @ symbol and allow us to include line breaks, special characters, and even whitespace without using escape sequences.

Here's an example of a multiline string using a verbatim string:

string str = @"This is a
multiline string
in C#.";
string str = @"This is a
multiline string
in C#.";
Dim str As String = "This is a
multiline string
in C#."
VB   C#

The string str contains three lines, and each line is separated by a line break. Notice the use of the @ symbol to create the verbatim string.

Escaping Characters in Verbatim Strings

There may be cases where you need to include double quotes within a verbatim string. To include double quotes within a verbatim string, you have to use double-double quotes. For example:

string str = @"This is a
""multiline""
string in C#.";
string str = @"This is a
""multiline""
string in C#.";
Dim str As String = "This is a
""multiline""
string in C#."
VB   C#

In this example, the string str contains the word "multiline" enclosed in double quotes, which is achieved by using double-double quotes within the verbatim string.

Concatenating Multiline Strings

You might often need to combine multiline strings with other strings or values. To concatenate a multiline string with other string values, you can use the '+' operator, just like you would with single line strings.

string name = "John";
string str = @"Hello, " + name + @",
Welcome to the
world of C# multiline strings!";
string name = "John";
string str = @"Hello, " + name + @",
Welcome to the
world of C# multiline strings!";
Dim name As String = "John"
Dim str As String = "Hello, " & name & ",
Welcome to the
world of C# multiline strings!"
VB   C#

We concatenated the multiline string with a single line string name.

Formatting Multiline Strings

When working with multiline strings, you may need to format them by including variables or expressions. To format a multiline string, you can use the '$' symbol for string interpolation.

int age = 25;
string str = $@"Hello, I am {age} years old,
and I am learning
C# multiline strings!";
int age = 25;
string str = $@"Hello, I am {age} years old,
and I am learning
C# multiline strings!";
Dim age As Integer = 25
Dim str As String = $"Hello, I am {age} years old,
and I am learning
C# multiline strings!"
VB   C#

We used string interpolation to include the value of the age variable within the multiline string.

Converting Multiline Strings to Single Line Strings

Sometimes, you may need to convert multiline strings into single line strings. To achieve this, you can use the Replace method to replace line breaks with a space or any other desired character.

string multilineString = @"This is a
multiline string
in C#.";

string singleLineString = multilineString.Replace(Environment.NewLine, " ");
string multilineString = @"This is a
multiline string
in C#.";

string singleLineString = multilineString.Replace(Environment.NewLine, " ");
Dim multilineString As String = "This is a
multiline string
in C#."

Dim singleLineString As String = multilineString.Replace(Environment.NewLine, " ")
VB   C#

We replaced the line breaks in the multiline string with a space, resulting in a single line string.

Handling Long Strings

You might often deal with very long strings that are difficult to read in your code. To make the code more readable, you can split long strings into multiple lines using the '+' operator.

string longString = "This is a very long string that " +
                    "needs to be split across " +
                    "multiple lines for better readability.";
string longString = "This is a very long string that " +
                    "needs to be split across " +
                    "multiple lines for better readability.";
Dim longString As String = "This is a very long string that " & "needs to be split across " & "multiple lines for better readability."
VB   C#

We split the long single line string into three parts and concatenated them using the '+' operator, making the code more readable.

Creating Multiline String Literals with Raw String Literals

In C# 10, a new feature was introduced called raw string literals. These allow us to create multiline string literals without using the '@' symbol. To create a raw string literal, we enclose the string in triple quotes, like this """. Raw string literals preserve all the characters, including line breaks, within the triple quotes. For example:

string str = """This is a
multiline string
using raw string literals in C# 10.""";
string str = """This is a
multiline string
using raw string literals in C# 10.""";
Dim str As String = """This is a multiline string using raw string literals in C# 10."""
VB   C#

We created a multiline string using raw string literals. Notice the use of triple quotes to enclose the string.

Escaping Characters in Raw String Literals

Similar to verbatim strings, we might need to include double quotes within our raw string literals. To do this, we can use double-double quotes. For example:

string str = """This is a
""multiline""
string using raw string literals in C# 10.""";
string str = """This is a
""multiline""
string using raw string literals in C# 10.""";
Dim str As String = """This is a ""multiline"" string using raw string literals in C# 10."""
VB   C#

We included double quotes within the raw string literal by using double-double quotes.

Combining Verbatim and Raw String Literals

In some cases, we may want to combine the features of both verbatim and raw string literals. This can be done by using the '@' symbol followed by triple quotes.

string str = @"""This is a
multiline string
using both verbatim and raw string literals in C# 10."""
string str = @"""This is a
multiline string
using both verbatim and raw string literals in C# 10."""
Dim str As String = """This is a
multiline string
using both verbatim and raw string literals in C# 10."""
VB   C#

In this example, we created a multiline string using both verbatim and raw string literals. Notice the use of the '@' symbol followed by triple quotes.

Generating PDFs with IronPDF and C#

In this section, we will explore how to use IronPDF, a powerful library that makes it easy to create, read, and edit PDF files in C# from HTML, in conjunction with C#

IronPDF's primary feature is HTML to PDF conversion. IronPDF preserves the layouts and style of web page content in its PDF form. Common uses of IronPDF include creating invoices, reports, and documentation.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

Installing IronPDF

To get started with IronPDF, you first need to install the IronPdf NuGet package. You can do this by executing the following command in your project's Package Manager Console:

Install-Package IronPdf

Alternatively, you can also search for "IronPDF" in the NuGet Package Manager and install it from there.

Creating a PDF from a C#

Once IronPDF is installed, you can create a PDF file from an HTML multiline string in just a few lines of code. Here's an example of how to do it:

string name = "John";
string age = "25";
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
<p>This is a
multiline string
used to generate a PDF
with IronPDF and dynamic content.</p>
</body>
</html>";

// Create a new PDF document
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(content).SaveAs("c://BioData.pdf");
string name = "John";
string age = "25";
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
<p>This is a
multiline string
used to generate a PDF
with IronPDF and dynamic content.</p>
</body>
</html>";

// Create a new PDF document
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(content).SaveAs("c://BioData.pdf");
Dim name As String = "John"
Dim age As String = "25"
Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
<p>This is a
multiline string
used to generate a PDF
with IronPDF and dynamic content.</p>
</body>
</html>"

' Create a new PDF document
Dim pdfDocument = New IronPdf.ChromePdfRenderer()
pdfDocument.RenderHtmlAsPdf(content).SaveAs("c://BioData.pdf")
VB   C#

C# Multiline String (How It Works For Developers) Figure 1 - PDF Document

In this example, we used string interpolation to include the name and age variables within our multiline string, making our PDF content dynamic and customizable. We created a multiline string with the content we wanted in the PDF. We then instantiated the ChromePdfRenderer class from the IronPDF namespace and used the RenderHtmlAsPdf method to convert the multiline string content into a PDF document. Finally, we saved the PDF document to a file called "BioData.pdf".

Conclusion

Throughout this tutorial, we have explored the versatile world of C# multiline strings and learned how to effectively create, manipulate, and format them. Additionally, we have discovered how to integrate C#

IronPDF offers a free trial, allowing you to test its capabilities before committing to a license, which starts from $749.

< PREVIOUS
What is Visual C++ Redistributable
NEXT >
C# If (How it Works for Developers)

Ready to get started? Version: 2024.5 just released

Start Free Trial Total downloads: 9,229,207
View Licenses >