DTOs Must be Immutable.

Zeeshan Ali
2 min readAug 4, 2023

--

DTO stands for “Data Transfer Object”, a simple class containing only fields and no business logic.

DTO is a good and practical design pattern for transferring data between different layers and components.

DTOs also help in improving performance by passing the only necessary data that reduces the network overhead.

DTOs are only used for transporting data between layers and components in an application so we need to make sure that the data should not be changed or altered unexpectedly. Your DTOs must be Immutable that ensures the unauthorized modifications of the data during the transport.

Immutable DTOs also help in passing the sensitive data between layers and components, it also ensures Data Security and Thread Safety. Immutable DTO can also be easily cached as its content is fixed.

See the below traditional implementation of the Immutable DTO.

public class CustomerDTO
{
public string Name { get; }
public string Email { get; }
public int CustomerId { get; }

public CustomerDTO(string name, string email, int customerId)
{
Name = name;
Email = email;
CustomerId = customerId;
}
}

// useage.
CustomerDTO customer = new CustomerDTO("Uncle Bob", "bob@example.com", 1);

Notice the properties in the above class have only getters (no setters) and these properties can only be set at time of object creation. You can’t set properties after object creation.

C# 9.0 has introduced a new type “Record” that is specifically designed to model immutable data for the same purpose like traditional immutable DTO.

We can do the same thing in a single line as we did in our previous example.

public record CustomerDTO(string Name, string Email, int CustomerId);

—; Please like and follow if you like this Article; —

Thank you.

--

--

Zeeshan Ali
Zeeshan Ali

Written by Zeeshan Ali

I am a Software Architect with 12 years of experience in Microsoft technologies. I specialize in designing and implementing high-performance, scalable solutions