When to Use Record vs Class vs Struct
  • Should I be using Record for all of my DTO classes that move data between controller and service layer?

  • Should I be using Record for all my request bindings since ideally I would want the request sent to the controller to be immutable for my asp.net API

What is a Record? Anthony Giretti  Introducing C# 9: Records

  public class HomeController 
  { 
    public IHttpAction Search([FromBody] SearchParameters searchParams)
    {
       _service.Search(searchParams);
    }
  }

should SearchParameters be made a Record?

1

3 Answers

Short version

Can your data type be a value type? Go with struct. No? Does your type describe a value-like, preferably immutable state? Go with record.

Use class otherwise. So...

  1. Yes, use records for your DTOs if it is one way flow.
  2. Yes, immutable request bindings are an ideal user case for a record
  3. Yes, SearchParameters are an ideal user case for a record.

For further practical examples of record use, you can check this repo.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.