search
Get Started
search
C# Records and Immutability Refactoring - Jetbrains Native Refactoring
zoom_in Click to enlarge

C# Records and Immutability Refactoring

description C# Records and Immutability Refactoring Overview

In C#, refactoring mutable classes into immutable `record` types is a major step towards safer, more predictable code, especially in concurrent environments. Records automatically generate value equality, proper hashing, and immutability guarantees. This pattern forces developers to treat data structures as immutable facts rather than mutable states, drastically simplifying multi-threaded logic.

help C# Records and Immutability Refactoring FAQ

What changes when a mutable C# class is refactored into a record?

A record gives the compiler value-based equality, generated hashing, a useful ToString method, and nondestructive copying with the with expression. A positional record class also creates init-only properties, so values cannot normally be changed after construction. [Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record)

Does a C# record guarantee deep immutability?

No. Record immutability is shallow: an init-only property cannot point to a different array after construction, but the contents of that array can still change. Use immutable collections or defensive copies when nested data must also stay unchanged. [Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record)

When were C# records introduced?

Records were introduced with C# 9 and the .NET 5 era. They are intended mainly for data-centric types such as value objects, messages, and DTOs rather than every class in an application. [Microsoft .NET Blog](https://devblogs.microsoft.com/dotnet/welcome-to-csharp-9-0/)

Should I refactor an Entity Framework Core entity into a C# record?

Usually not. Microsoft notes that records are a poor fit for Entity Framework Core entities because EF Core relies on reference equality and tracks object identity. [Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record)

Reviews & Comments

Write a Review

rate_review

Be the first to review

Share your thoughts with the community and help others make better decisions.

Save to your list

Save your favorites and follow how their scores change over time.

Save favorites
Track changes
Compare scores

Already have an account? Sign in

Compare Items

See how they stack up against each other

Comparing
VS
Select 1 more item to compare