Saltar al pie de página
.NET AYUDA

C# Record (Cómo Funciona para Desarrolladores)

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.

Preguntas Frecuentes

¿Cómo puedo usar registros en C# para generar un PDF?

Los registros de C# se pueden usar para almacenar datos de manera eficiente, que luego pueden ser utilizados por IronPDF para generar documentos PDF. Puedes crear un registro para contener los datos necesarios y usar IronPDF para renderizar estos datos en un formato PDF.

¿Cuáles son los beneficios de usar registros de C#?

Los registros de C# ofrecen varios beneficios, incluida una sintaxis simplificada, modelos de datos inmutables, igualdad basada en valores y soporte para herencia. Estas características hacen que los registros sean adecuados para crear tipos centrados en datos concisos y confiables.

¿Cómo manejan la igualdad los registros en C#?

Los registros en C# enfatizan la igualdad basada en valores. Esto significa que dos instancias de registro se consideran iguales si los valores de sus propiedades coinciden, independientemente de su ubicación en memoria.

¿Cómo declaras un registro en C#?

Un registro en C# se declara usando la palabra clave record seguida del tipo (clase o estructura) y el nombre del registro. Por ejemplo, public record class Person(string FirstName, string LastName);.

¿Cuál es la diferencia entre clases de registros y estructuras de registros?

Las clases de registros son tipos de referencia, mientras que las estructuras de registros son tipos de valor. Ambos proporcionan inmutabilidad y comparación basada en valores, pero difieren en la asignación de memoria y casos de uso.

¿Puedes modificar las propiedades de un registro de C# después de su creación?

Los registros de C# están diseñados para ser inmutables, lo que significa que las propiedades no se pueden cambiar después de que se crea el registro. Sin embargo, puedes realizar una mutación no destructiva para crear una nueva instancia de registro con propiedades modificadas.

¿Cómo mejora IronPDF las aplicaciones de C#?

IronPDF mejora las aplicaciones de C# proporcionando capacidades sólidas para generar, editar y manipular documentos PDF. Permite a los desarrolladores crear PDFs a partir de contenido HTML, lo que lo convierte en una herramienta versátil para la gestión de documentos.

¿Cómo se instala IronPDF en un proyecto .NET?

Puedes instalar IronPDF en un proyecto .NET usando el Gestor de Paquetes NuGet en Visual Studio o ejecutando el comando Install-Package IronPdf en la Consola del Gestor de Paquetes.

¿Cómo funciona la mutación no destructiva en los registros de C#?

La mutación no destructiva en los registros de C# te permite crear una nueva instancia de registro a partir de una existente con algunas propiedades modificadas, sin alterar la instancia original.

¿Para qué se utiliza una biblioteca de PDF en el desarrollo de C#?

Una biblioteca de PDF como IronPDF se utiliza en el desarrollo de C# para generar, editar y manipular documentos PDF. Ayuda a los desarrolladores a integrar eficientemente funcionalidades de PDF en sus aplicaciones.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más