Record types - Csharp

A record in C# is a class and struct that provides special syntax and behavior for working with data models. The record modifier instructs the compiler to integrate members which is useful for types whose primary role is storing data. These members include an overload of ToString() and members that support value equality.

When to use records

Suppose we have a scenario where we use the record in place of class or struct.

  • When we want to define a data model that depends on value equality.
  • When we want to define a type for which objects are immutable.

Value Equality

For records, value equality means that two variables of a record type are equal if the types match and all property and field values ​​are equal.

Immutable

An immutable type prevents us from changing any of the properties or field values ​​of an object after it has been instantiated.

Create a Record Type

csharp
public record Person(string FirstName, string LastName, int Age);

This above code creates a record type named Person with three properties: FirstName, LastName, and Age. The properties are automatically generated as public read-only members.

Use Record Type

Here, we use the above-created record type:

csharp
var person1 = new Person("John", "Doe", 30); var person2 = new Person("John", "Doe", 30); Console.WriteLine(person1 == person2); // Output: True (value comparison)

Benefits of Using Record Types

  • Improved Readability: Record types promote a more declarative style of programming, making code easier to read and understand.
  • Enhanced Immutability: The inherent immutability of record types helps prevent unintended side effects and ensures data consistency.
  • Simplified Equality and Hashing: Automatic generation of Equals and GetHashCode methods reduces boilerplate code and simplifies comparison operations.
  • Efficient Data Structures: Record types are often used as data structures in functional programming paradigms, where immutability and value semantics are essential.

Example

In the following example, we define a public record that uses positional parameters to declare and instantiate a record. It then prints the type name and property values:

csharp
public record Person(string FirstName, string LastName); public static class Program { public static void Main() { Person person = new Person("Aman", "Gupta"); Console.WriteLine($"Person: {person.FirstName} {person.LastName}"); } }

Example

In this example, we will demonstrate value equality in records:

csharp
public record Person(string FirstName, string LastName, string[] PhoneNumbers); public static class Program { public static void Main() { var phoneNumbers = new string[2]; Person person1 = new("Aman", "Gupta", phoneNumbers); Person person2 = new("Aman", "Gupta", phoneNumbers); Console.WriteLine(person1 == person2); // output: True person1.PhoneNumbers[0] = "9144455678"; Console.WriteLine(person1 == person2); // output: True Console.WriteLine(ReferenceEquals(person1, person2)); // output: False } }

Example

The following example demonstrates the use of a with expression to copy an immutable object and change one of the properties:

csharp
public record Person(string FirstName, string LastName) { public required string[] PhoneNumbers { get; init; } } public class Program { public static void Main() { Person person1 = new("Aman", "Gupta") { PhoneNumbers = new string[1] }; Console.WriteLine(person1); // output: Person { FirstName = Aman, LastName = Gupta, PhoneNumbers = System.String[] } Person person2 = person1 with { FirstName = "John" }; Console.WriteLine(person2); // output: Person { FirstName = John, LastName = Gupta, PhoneNumbers = System.String[] } Console.WriteLine(person1 == person2); // output: False person2 = person1 with { PhoneNumbers = new string[1] }; Console.WriteLine(person2); // output: Person { FirstName = Aman, LastName = gupta, PhoneNumbers = System.String[] } Console.WriteLine(person1 == person2); // output: False person2 = person1 with { }; Console.WriteLine(person1 == person2); // output: True } }

In summary, C# records are a powerful addition to the language, providing a convenient way to represent immutable data structures. By understanding their special characteristics and benefits, we can effectively use them in our C# applications to write clean, maintainable, and efficient code.

line

Copyrights © 2024 letsupdateskills All rights reserved