| Memory Management in C# | Pattern Matching in C# | |
Records in C# |
Records in C# are special reference types introduced in C# 9.0 designed to make working with immutable data objects easier. They are ideal for data-centric models (like DTOs) where you primarily care about the data the object holds, not its identity.
Unlike regular classes, records automatically provide value-based equality (two record instances are equal if all their properties are equal), built-in immutability, and concise syntax for creating and cloning objects.
public record Person(string Name, int Age);
This defines a record with two properties: Name and Age. You can instantiate it like this:
var p1 = new Person("Alice", 25);
var p2 = new Person("Alice", 25);
Console.WriteLine(p1 == p2); // True - value equality
Here, == compares property values, not object references (unlike classes).
var p3 = p1 with { Age = 30 };
Console.WriteLine(p3); // Output: Person { Name = Alice, Age = 30 }
The with expression creates a copy of the record with modified properties while keeping the original immutable.
public record Employee
{
public string Name { get; init; }
public string Department { get; init; }
public int Salary { get; init; }
```
public void DisplayInfo() =>
Console.WriteLine($"{Name} works in {Department} earning {Salary}");
```
}
init accessors to maintain immutability while allowing initialization.with expressions instead of modifying existing record instances.with expressions creates new instances — may increase memory usage for large data.init-only properties mean you can’t modify data after creation — design accordingly.Deconstruct and equality methods).Equals, GetHashCode, or ToString).switch expressions.with expression.class PersonClass
{
public string Name { get; set; }
public int Age { get; set; }
}
var c1 = new PersonClass { Name = "Alice", Age = 25 };
var c2 = new PersonClass { Name = "Alice", Age = 25 };
Console.WriteLine(c1 == c2); // False (reference comparison)
record PersonRecord(string Name, int Age);
var r1 = new PersonRecord("Alice", 25);
var r2 = new PersonRecord("Alice", 25);
Console.WriteLine(r1 == r2); // True (value comparison)
| Memory Management in C# | Pattern Matching in C# | |