Here we are going to learn to use C# 9.0 feature record type with ASP.NET Core 5.0. Let's first understand a few keywords.
What is C# 9.0?
C# 9.0 is the latest version of the C# language and it is supported on .NET 5.
Features
- Records
- Init only setters
- Top-level statements
- Pattern matching enhancements
- Fit and finish features
- Support for code generators
- etc
What is ASP.NET Core?
ASP.NET Core is a cross-platform, free and open-source web framework.
What is ASP.NET Core 5.0?
ASP.NET Core is the latest version of the ASP.NET Core framework and it was released in 2020. and it Supports C# 9.0.
Features
- Model binding and validation with C# 9 record types
- Improvements to DynamicRouteValueTransformer
- OpenAPI Specification on by default
- Azure API Management Import
- Better launch experience for web API projects
- Blazor Performance improvements
- New InputFile component
- New InputRadio and InputRadioGroup components
The C# 9 record type is used for data transfer objects where immutable is valuable.
We can transfer data back and forth from an ASP.NET Core Web API.
I have created a couple of record types to transfer data and that represents adding a new student and getting a student from the web API.
- public record StudentGetResponse
- {
- public int ID { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public DateTime EnrollmentDate { get; set; }
- }
-
- public record StudentAddRequest
- {
- [Required]
- public string FirstName { get; set; }
- [Required]
- public string LastName { get; set; }
- public DateTime EnrollmentDate { get; set; }
- }
Then I have created APIController with Getting and Post actions.
Post action is accepting a new student.
- [HttpPost]
- public async Task<ActionResult<StudentGetResponse>> Post(StudentAddRequest student)
- {
- return await _studentService.Add(student);
- }
Output
- {
- "id": 2002,
- "firstName": "Lalji",
- "lastName": "Dhameliya",
- "enrollmentDate": "2021-04-30T12:42:45.1454261Z"
- }
Get action is returning a student by id.
- [HttpGet("{id}")]
- public async Task<ActionResult<StudentGetResponse>> Get(int id)
- {
- return await _studentService.Get(id);
- }
Output
- {
- "id": 1,
- "firstName": "Lalji",
- "lastName": "Dhameliya",
- "enrollmentDate": "2021-04-30T10:51:59.833"
- }
C# 9 record type is fully supported by ASP.NET Core 5.0 during model binding and also we can use DataAnnotations model validation as provde example in Post API.
Wrap Up
For this, we need to use the latest version of Visual Studio 2019 to get ASP.NET Core 5 and C# 9 and you can also find this in the attached .zip file.