Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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.
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.
There are two main types of records in C#:
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)
This declaration includes positional parameters for FirstName and LastName, which under the hood, generate public properties and a primary constructor for these properties.
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.
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)
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.
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
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.
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";
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)
This Employee record extends Person, adding the additional Department property.
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" }
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)
IronPDF is a PDF library for .NET developers, designed for generating, editing, and manipulating PDF documents within C# applications. IronPDF supports rendering PDFs from HTML, 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 webforms into PDF files. IronPDF operates efficiently across various application types, including forms applications, server applications, and web applications.
Installing IronPDF is straightforward and can be accomplished via the NuGet Package Manager in Visual Studio. Follow these steps:
Alternatively, you can install it using the Package Manager Console with the command:
Install-Package 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
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.
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. License before purchasing the license.
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 free trial before deciding on a purchase. If you find the software meets your needs, you can buy a license starting at $749.
9 .NET API products for your office documents