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...
Should I be using
Recordfor all of my DTO classes that move data between controller and service layer?Should I be using
Recordfor 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?
3 Answers
Must Read
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...
- Yes, use
records for your DTOs if it is one way flow. - Yes, immutable request bindings are an ideal user case for a
record - Yes,
SearchParametersare an ideal user case for arecord.
For further practical examples of record use, you can check this repo.