Zum Fußzeileninhalt springen
.NET HILFE

C# Record (Funktionsweise für Entwickler)

C# record is a powerful feature introduced to ease the creation of immutable data models and to enhance the coding experience by reducing boilerplate code. This tutorial aims to simplify the concept of records in C# for beginners, guiding you through their syntax, usage, and advantages.

Whether you're dealing with data transfer objects, configurations, or simply need an efficient way to represent data, C# records offer a concise and developer-friendly approach. We'll also discuss IronPDF later in the article.

What is a C# Record?

A record in C# is a reference type that provides a simplified syntax for defining immutable data models. Unlike traditional class definitions, a record emphasizes value-based equality rather than reference equality. This means two record instances are considered equal if their property values are the same, not merely because they refer to the same object location in memory.

Record Types: Class and Struct

There are two main types of records in C#:

  • Record class: The default record type, which is a reference type.
  • Record struct: Introduced for scenarios requiring value types, these are immutable by default and offer value-based comparison similar to record classes.

Record Declaration

Declaring a record is straightforward. You can define a record using the record keyword followed by the type (class or struct) and the name of the record. For example, a simple person record can be declared as:

public record class Person(string FirstName, string LastName);
public record class Person(string FirstName, string LastName);
'INSTANT VB TODO TASK: C# 'records' are not converted by Instant VB:
'public record class Person(string FirstName, string LastName)
$vbLabelText   $csharpLabel

This declaration includes positional parameters for FirstName and LastName, which under the hood, generate public properties and a primary constructor for these properties.

The Immutable Nature of Records

Records are designed to be immutable, meaning once a record instance is created, its property values cannot be changed. This immutability is crucial for creating predictable and thread-safe applications, especially when dealing with concurrent operations.

Immutable Record Struct

An immutable record struct is declared similarly to a record class but using the record struct syntax. It combines the immutability and value-based comparison of records with the performance benefits of a value type:

public readonly record struct ImmutablePerson(string FirstName, string LastName);
public readonly record struct ImmutablePerson(string FirstName, string LastName);
'INSTANT VB TODO TASK: C# 'records' are not converted by Instant VB:
'public readonly record struct ImmutablePerson(string FirstName, string LastName)
$vbLabelText   $csharpLabel

Working with Records

Records simplify the creation and use of data-centric types. They support inheritance, allow non-destructive mutation, and provide built-in formatting for easier debugging. Let's explore these features through examples.

Creating and Comparing Records

Consider the following example where we create two instances of a person record:

var person1 = new Person("Iron", "Software");
var person2 = new Person("Iron", "Software");
Console.WriteLine(person1 == person2); // Output: True
var person1 = new Person("Iron", "Software");
var person2 = new Person("Iron", "Software");
Console.WriteLine(person1 == person2); // Output: True
Dim person1 = New Person("Iron", "Software")
Dim person2 = New Person("Iron", "Software")
Console.WriteLine(person1 = person2) ' Output: True
$vbLabelText   $csharpLabel

Despite person1 and person2 being two distinct instances, they are considered equal based on their property values, showcasing value-based equality. This is a significant departure from the reference types' default behavior, which focuses on reference equality.

Immutable Properties

By design, record properties are immutable. This means you cannot change the property values of a record instance after it has been created.

// This will result in a compilation error
// person1.FirstName = "Jane";
// This will result in a compilation error
// person1.FirstName = "Jane";
' This will result in a compilation error
' person1.FirstName = "Jane";
$vbLabelText   $csharpLabel

Inheritance with Records

Records support inheritance, allowing you to create a hierarchy of data models. Here's how you can extend a base record:

public record Employee(string FirstName, string LastName, string Department) : Person(FirstName, LastName);
public record Employee(string FirstName, string LastName, string Department) : Person(FirstName, LastName);
'INSTANT VB TODO TASK: C# 'records' are not converted by Instant VB:
'public record Employee(string FirstName, string LastName, string Department) : Person(FirstName, LastName)
$vbLabelText   $csharpLabel

This Employee record extends Person, adding the additional Department property.

Advanced Record Features

Non-Destructive Mutation

Records provide a built-in method for creating a new record instance from an existing one with some properties modified, known as non-destructive mutation.

var updatedPerson = person1 with { FirstName = "Jane" };
var updatedPerson = person1 with { FirstName = "Jane" };
'INSTANT VB TODO TASK: C# 'with expressions' are not converted by Instant VB:
'var updatedPerson = person1 with { FirstName = "Jane" }
$vbLabelText   $csharpLabel

Built-in Formatting

Records come with built-in formatting for easier debugging and logging, automatically providing a string representation of their properties.

Console.WriteLine(person1);
Console.WriteLine(person1);
Console.WriteLine(person1)
$vbLabelText   $csharpLabel

Advantages of Using C# Records

  • Simplified Syntax: Records reduce the need for boilerplate code, making your models more concise and readable.
  • Immutable Data Models: The immutable nature of records helps in creating thread-safe applications.
  • Value-Based Equality: Records use value-based equality instead of reference equality, ideal for data-centric types.
  • Support for Inheritance: Records can inherit from other records, allowing for code reuse and hierarchical data models.

Introduction to IronPDF: A C# PDF Library

C# Record (How It Works For Developers): Figure 1

IronPDF Overview is a PDF library for .NET developers, designed for generating, editing, and manipulating PDF documents within C# applications. IronPDF supports rendering PDFs from HTML content, CSS, Images, and JavaScript.

Its core capability lies in creating PDF documents from web content, offering a streamlined approach to converting HTML strings, URLs, and ASPX web forms into PDF files. IronPDF operates efficiently across various application types, including forms applications, server applications, and web applications.

How to Install the IronPDF Library

Installing IronPDF is straightforward and can be accomplished via the NuGet Package Manager in Visual Studio. Follow these steps:

  1. In Visual Studio, navigate to Solution Explorer, right-click on References, and select Manage NuGet Packages.
  2. In the NuGet Package Manager, select Browse and search for "IronPdf".
  3. Find the IronPDF package and click Install.

C# Record (How It Works For Developers): Figure 2

Alternatively, you can install it using the Package Manager Console with the command:

Install-Package IronPdf

Example: Using C# Record with IronPDF

Let's consider a practical example where we use a C# record to hold data that we then use to generate a PDF document with IronPDF:

public record Person(string FirstName, string LastName);

class Program
{
    static void Main(string[] args)
    {
        // Create an instance of the Person record.
        var person = new Person("Iron", "Developer");

        // Initialize a new renderer object for generating PDF files using Chrome's rendering engine.
        var renderer = new IronPdf.Rendering.ChromePdfRenderer();

        // Render an HTML string as a PDF document.
        var pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {person.FirstName} {person.LastName}</p>");

        // Save the PDF to the specified location.
        pdf.SaveAs("PersonRecord.pdf");
    }
}
public record Person(string FirstName, string LastName);

class Program
{
    static void Main(string[] args)
    {
        // Create an instance of the Person record.
        var person = new Person("Iron", "Developer");

        // Initialize a new renderer object for generating PDF files using Chrome's rendering engine.
        var renderer = new IronPdf.Rendering.ChromePdfRenderer();

        // Render an HTML string as a PDF document.
        var pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {person.FirstName} {person.LastName}</p>");

        // Save the PDF to the specified location.
        pdf.SaveAs("PersonRecord.pdf");
    }
}
'INSTANT VB TODO TASK: C# 'records' are not converted by Instant VB:
'public record Person(string FirstName, string LastName)

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create an instance of the Person record.
		Dim person As New Person("Iron", "Developer")

		' Initialize a new renderer object for generating PDF files using Chrome's rendering engine.
		Dim renderer = New IronPdf.Rendering.ChromePdfRenderer()

		' Render an HTML string as a PDF document.
		Dim pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {person.FirstName} {person.LastName}</p>")

		' Save the PDF to the specified location.
		pdf.SaveAs("PersonRecord.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

This example creates a simple Person record and then uses IronPDF to generate a PDF document displaying the person's name. It showcases how seamlessly C# records can integrate with PDF generation in .NET applications.

C# Record (How It Works For Developers): Figure 3

IronPDF Licensing

C# Record (How It Works For Developers): Figure 4

IronPDF is a commercial product offering various licenses tailored to different needs, including individual and commercial options. Each purchase comes with a lifetime license and a 30-day money-back guarantee. Explore IronPDF Licensing Options before purchasing the license.

Conclusion

C# records represent a significant step forward in simplifying data modeling in .NET applications. By understanding and leveraging records, developers can create more reliable, maintainable, and readable code bases.

Whether you're working on large-scale applications or simple data structures, the features offered by records, from immutability to value-based equality, make them an indispensable tool in your C# toolkit.

IronPDF provides an opportunity to test its features using the IronPDF Free Trial before deciding on a purchase. If you find the software meets your needs, you can buy a license starting at $799.

Häufig gestellte Fragen

Wie kann ich Records in C# verwenden, um ein PDF zu erzeugen?

C#-Records können verwendet werden, um Daten effizient zu speichern, die dann von IronPDF zur Erstellung von PDF-Dokumenten genutzt werden können. Sie können ein Record erstellen, um die notwendigen Daten zu halten, und IronPDF verwenden, um diese Daten in ein PDF-Format zu rendern.

Was sind die Vorteile der Verwendung von C#-Records?

C#-Records bieten mehrere Vorteile, darunter vereinfachte Syntax, unveränderliche Datenmodelle, wertbasierte Gleichheit und Unterstützung für Vererbung. Diese Funktionen machen Records geeignet für die Erstellung prägnanter und zuverlässiger datenzentrierter Typen.

Wie handhaben Records die Gleichheit in C#?

Records in C# betonen die wertbasierte Gleichheit. Das bedeutet, dass zwei Record-Instanzen als gleich gelten, wenn ihre Eigenschaftswerte übereinstimmen, unabhängig von ihrem Speicherort.

Wie erklärt man ein Record in C#?

Ein Record in C# wird mit dem record-Schlüsselwort deklariert, gefolgt von dem Typ (Klasse oder Struktur) und dem Namen des Records. Zum Beispiel: public record class Person(string FirstName, string LastName);.

Was ist der Unterschied zwischen Record-Klassen und Record-Strukturen?

Record-Klassen sind Referenztypen, während Record-Strukturen Werttypen sind. Beide bieten Unveränderlichkeit und wertbasierte Vergleichbarkeit, unterscheiden sich jedoch in Bezug auf Speicherzuordnung und Anwendungsfälle.

Können Sie die Eigenschaften eines C#-Records nach der Erstellung ändern?

C#-Records sind dafür ausgelegt, unveränderlich zu sein, was bedeutet, dass die Eigenschaften nach der Erstellung des Records nicht geändert werden können. Sie können jedoch eine nicht-destruktive Mutation durchführen, um eine neue Record-Instanz mit geänderten Eigenschaften zu erstellen.

Wie verbessert IronPDF C#-Anwendungen?

IronPDF verbessert C#-Anwendungen, indem es robuste Funktionen zum Erstellen, Bearbeiten und Verarbeiten von PDF-Dokumenten bietet. Es ermöglicht Entwicklern, PDFs aus HTML-Inhalten zu erstellen und ist ein vielseitiges Werkzeug für das Dokumentenmanagement.

Wie installiert man IronPDF in einem .NET-Projekt?

Sie können IronPDF in einem .NET-Projekt über den NuGet-Paket-Manager in Visual Studio installieren oder indem Sie den Befehl Install-Package IronPdf in der Paket-Manager-Konsole ausführen.

Wie funktioniert die nicht-destruktive Mutation in C#-Records?

Nicht-destruktive Mutation in C#-Records ermöglicht es Ihnen, eine neue Record-Instanz aus einer bestehenden zu erstellen, bei der einige Eigenschaften geändert wurden, ohne die ursprüngliche Instanz zu beeinflussen.

Wofür wird eine PDF-Bibliothek in der C#-Entwicklung verwendet?

Eine PDF-Bibliothek wie IronPDF wird in der C#-Entwicklung zum Erstellen, Bearbeiten und Verarbeiten von PDF-Dokumenten verwendet. Sie hilft Entwicklern, PDF-Funktionalitäten effizient in ihre Anwendungen zu integrieren.

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