Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#

What are records in C# 9.0?

Ayesha Naeem

C# 9.0 provides the liberty to define a reference type using the keyword record. A record provides easy-to-use syntax and built-in functionalities for handling data and creating immutable properties.

You can create immutable properties using record in the following ways.

  1. Positional parameters

    The positional parameters in records can be set at the time of initialization using a simple syntax as shown below:

public class Program
{
	
	public record Student(string FirstName, string LastName)
	
	public static void Main()
	{
		Student student1 = new("Sam", "Johnson") 	
	}
}
  1. init accessors

    The user can specify the init accessor type in the record properties. The user can then set these properties using initializer property syntax. The properties remain immutable after the initialization phase.

public class Program
{
	
	public record Student
  {
    public string FirstName { get; init; }
    public string LastName { get; init; }
  }
	
	public static void Main()
	{
		Student student1 = new("Sam", "Johnson") 
	}
}

Important points about records

Records provide the following features:

  1. A simple way to create immutable properties.
  2. Useful methods for handling data-centric models that include:
  3. Inheritance support.

RELATED TAGS

c#

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring