.NET HELP

C# Record (How It Works For Developers)

Published April 3, 2024
Share:

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)
VB   C#

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)
VB   C#

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
VB   C#

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";
VB   C#

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)
VB   C#

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" }
VB   C#

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)
VB   C#

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)
    {
        var person = new Person("Iron", "Developer");
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {person.FirstName} {person.LastName}</p>");
        pdf.SaveAs("PersonRecord.pdf");
    }
}
public record Person(string FirstName, string LastName);
class Program
{
    static void Main(string [] args)
    {
        var person = new Person("Iron", "Developer");
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {person.FirstName} {person.LastName}</p>");
        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)
		Dim person As New Person("Iron", "Developer")
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {person.FirstName} {person.LastName}</p>")
		pdf.SaveAs("PersonRecord.pdf")
	End Sub
End Class
VB   C#

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 $749.

< PREVIOUS
C# Using Statement (How It Works For Developers)
NEXT >
C# Action (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >