Zum Fußzeileninhalt springen
.NET HILFE

C# Zeichenfolgeninterpolation (Wie es für Entwickler funktioniert)

What is String Interpolation?

Programmers can create strings using string interpolation, which involves immediately evaluating and inserting expressions or variables into the constant string object literal. Verbatim strings containing placeholders that are replaced by the values of specified expressions or variables can be created with interpolated strings.

Compared to more conventional techniques like string concatenation or the use of format string specifiers, interpolated string representation makes it easier to combine text with dynamic data in a variety of programming languages that allow this feature, making code more legible and concise. In this article, we are going to learn about the C# string interpolation feature in C# expression result.

The following are the resulting string interpolation features:

  1. Placeholder Syntax: To insert expressions or variables into a result string, string interpolation uses a particular syntax. Typically, special symbols or characters (such as {}, $(), {{}}, etc.) enclose the placeholders for string interpolation.
  2. Evaluation of Expressions: At runtime, the variables or expressions included in the placeholders are evaluated and their results are immediately placed into the raw string.
  3. Better Readability: By enabling developers to directly put values into strings without explicitly converting or concatenating values, the readability of code is improved.

How to use String Interpolation

  1. Create a new C# project.
  2. Make sure the required C# version has been installed.
  3. Create a string interpolation using the symbols or characters.
  4. Use the interpolated string as required.
  5. Run the code.

String Interpolation in C#

String interpolation in C# allows developers to embed expressions or variables directly into string literals. It simplifies the process of constructing multi-line strings by providing a concise and readable syntax. If we use string interpolation directly, the compiler will place string.Format method in its place.

Components of the literal string interpolation structure:

  • The $ sign indicates that the string literal is interpolated and comes before it. It sets ordinary string literals apart from interpolated strings.
  • String Literal with Placeholders: Curly braces {} enclose placeholders for expressions or variables inside the string literal designated for interpolation with $. These placeholders show the locations where the expression or variable values will be entered.
  • Expressions or Variables within Placeholders: In the final interpolated string, placeholders will be replaced by the values of the expressions or variables enclosed in curly braces ({}).
  • Final Interpolated String: This is the string that remains after interpolation, where placeholders have been replaced with the evaluated values of variables or expressions.

Structure Of Interpolation C#

Add the $ sign to the start of a string literal to indicate that it is an interpolated string. White space cannot appear between the $ and the " that starts a string literal.

{<interpolationExpression>[,<alignment>][:<formatString>]} //constant expression
{<interpolationExpression>[,<alignment>][:<formatString>]} //constant expression
If True Then
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'	<interpolationExpression>[,<alignment>][:<formatString>]} 'constant expression
$vbLabelText   $csharpLabel

String Interpolation with Verbatim and Raw Strings

Use several $ characters to begin an interpolated raw string literal to incorporate { and } characters in the returned string. Any sequence of { or } characters that is less than the total number of $ characters is inserted into the output string when you do that. To encapsulate any interpolation expression in that string, the number of braces used must match the amount of $ characters. As demonstrated by the following example below:

int x = 25;
Console.WriteLine($"square of {x} is {Math.Sqrt(x)}"); // Interpolated string output
int x = 25;
Console.WriteLine($"square of {x} is {Math.Sqrt(x)}"); // Interpolated string output
Dim x As Integer = 25
Console.WriteLine($"square of {x} is {Math.Sqrt(x)}") ' Interpolated string output
$vbLabelText   $csharpLabel

Output:

C# String Interpolation (How It Works For Developer): Figure 1 - String Message Output using String Interpolation Method

String Interpolation Feature With IronPDF

A highlight of IronPDF is its HTML to PDF conversion capabilities, preserving all layouts and styles. It converts web content into PDFs, perfect for reports, invoices, and documentation. You can easily convert HTML files, URLs, and HTML strings to PDFs.

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
$vbLabelText   $csharpLabel

Install IronPDF

Get the IronPDF library for seamless PDF generation as it is required for the next fix. To do this, enter the following code into the Package Manager:

Install-Package IronPdf

C# String Interpolation (How It Works For Developer): Figure 2 - Install IronPDF

Alternatively, you may use the NuGet Package Manager to search for the package "IronPDF". We may pick and download the necessary package from this list of all the NuGet packages associated with IronPDF.

C# String Interpolation (How It Works For Developer): Figure 3 - IronPDF Packages

String Interpolation Using IronPDF

The example code shows how we can create a PDF using the string interpolation method and interpolated expression. For a single interpolation expression, alignment specifiers and format strings can be combined.

using IronPdf;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string [] args)
        {
            int x = 25;
            // Define the interpolated string
            var outputstr = $@"square of <b>{x}</b> is <b>{Math.Sqrt(x)}</b>";
            // Create a PDF using IronPDF
            var pdfcreate = ChromePdfRenderer.StaticRenderHtmlAsPdf(outputstr);
            // Save the PDF as a file
            pdfcreate.SaveAs("demo.pdf");
        }
    }
}
using IronPdf;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string [] args)
        {
            int x = 25;
            // Define the interpolated string
            var outputstr = $@"square of <b>{x}</b> is <b>{Math.Sqrt(x)}</b>";
            // Create a PDF using IronPDF
            var pdfcreate = ChromePdfRenderer.StaticRenderHtmlAsPdf(outputstr);
            // Save the PDF as a file
            pdfcreate.SaveAs("demo.pdf");
        }
    }
}
Imports IronPdf

Namespace ConsoleApp1
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			Dim x As Integer = 25
			' Define the interpolated string
			Dim outputstr = $"square of <b>{x}</b> is <b>{Math.Sqrt(x)}</b>"
			' Create a PDF using IronPDF
			Dim pdfcreate = ChromePdfRenderer.StaticRenderHtmlAsPdf(outputstr)
			' Save the PDF as a file
			pdfcreate.SaveAs("demo.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

In the above code, the given string interpolation helps us convert the string representation into the desired output string name. We are also using multiple strings to interpolate into a single string. And with the help of the IronPDF, we are creating the PDF for the formatted strings. Likewise, we can create any number of PDF string representations into a PDF with the help of IronPDF. We can also format strings using the string.Format method.

Result:

C# String Interpolation (How It Works For Developer): Figure 4 - Output

To know more about the IronPDF, refer to the IronPDF documentation.

Conclusion

To sum up, C#'s string interpolation is a strong and effective feature that makes it easier to create strings by allowing expressions to be directly embedded into them. When compared to conventional string concatenation or formatting techniques, it provides a syntax that is easier to read and comprehend using opening and closing braces.

IronPDF offers a permanent license, upgrade options, a year of software maintenance, and a 30-day money-back guarantee in the $799 Lite bundle. Users can evaluate the product in practical application settings for thirty days during the watermarked trial period. Please visit the supplied IronPDF pricing and licensing page to learn more about IronPDF's costs, licensing, and trial version. To learn more about the various Iron Software products and libraries, check their website.

Häufig gestellte Fragen

Was ist String-Interpolation in C#?

Die String-Interpolation in C# ermöglicht es Entwicklern, Ausdrücke oder Variablen direkt in String-Literale einzubetten, wodurch der Prozess des Erstellens von Strings vereinfacht wird, indem eine prägnante und lesbare Syntax bereitgestellt wird.

Wie kann ich String-Interpolation verwenden, um PDFs in C# zu erstellen?

Sie können String-Interpolation verwenden, um Daten dynamisch in HTML-Inhalte einzubetten, die dann mit den Rendering-Methoden von IronPDF in ein PDF konvertiert werden können.

Kann String-Interpolation verwendet werden, um HTML-Inhalte für die PDF-Erstellung zu formatieren?

Ja, String-Interpolation kann verwendet werden, um HTML-Inhalte dynamisch mit Ausdrücken oder Variablen zu formatieren, die dann mit Tools wie IronPDF in PDFs gerendert werden können.

Welche Syntax wird für die String-Interpolation in C# verwendet?

Die Syntax für die String-Interpolation in C# beinhaltet das Setzen eines '$'-Zeichens vor das String-Literal und die Verwendung von geschweiften Klammern '{}' zur Einbindung von Ausdrücken oder Variablen.

Wie integriert sich IronPDF mit String-Interpolation?

IronPDF kann HTML-Inhalte in PDF-Dokumente rendern, sodass Entwickler String-Interpolation verwenden können, um Daten dynamisch in HTML einzufügen, bevor sie in PDF konvertiert werden.

Welche Vorteile bietet die Verwendung von String-Interpolation gegenüber herkömmlichen Methoden zur String-Formatierung?

String-Interpolation bietet eine verbesserte Lesbarkeit und Prägnanz im Vergleich zu String-Konkatenation und Formatangaben, wodurch der Code einfacher zu verstehen und zu warten ist.

Wie kann IronPDF verwendet werden, um HTML-Strings in PDF-Dokumente zu konvertieren?

IronPDF kann HTML-Strings in PDF-Dokumente konvertieren, indem Methoden wie RenderHtmlAsPdf verwendet werden, die HTML-Inhalte als Eingabe nehmen und ein formatiertes PDF ausgeben.

Welche Rolle spielt das '$'-Zeichen in der String-Interpolation?

Das '$'-Zeichen wird verwendet, um anzuzeigen, dass ein String ein interpolierter String ist, sodass die Ausdrücke in geschweiften Klammern '{}' ausgewertet und in die Ausgabe eingefügt werden können.

Wie formatiert man Ausdrücke innerhalb einer String-Interpolation in C#?

Ausdrücke innerhalb einer String-Interpolation können mit Ausrichtungs- und Formatangaben innerhalb der geschweiften Klammern formatiert werden, um angepasste Ausgabeformate zu ermöglichen.

Wie kann die String-Interpolation die PDF-Inhaltserstellung verbessern?

String-Interpolation ermöglicht das dynamische Einbetten von Inhalten in HTML, bevor sie in PDF konvertiert werden, was die Fähigkeit verbessert, personalisierte und formatierte Dokumente effizient zu erstellen.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen