Records in C# 9.0 provide positional syntax to declare and initialize property values of an instance.
The compiler makes the properties public init-only auto-implemented when the user employs positional syntax to declare and initialize properties.
The compiler also creates a constructor that accepts values and assigns them to properties according to their position. Additionally, a deconstruct method with an out
parameter for each positional parameter is created when there are more than two positional properties.
The following example demonstrates how to use the positional syntax for property definition with C# 9.0 records.
The following code creates a record Course
and initializes the init-only
properties without an explicit constructor, using the positional syntax.
using System;namespace Educative{// create recordpublic record Course(string Name , int Price );class positionalProperty{static void Main(string[] args){//initialize using positonal syntaxvar course = new Course("Intro to programming", 35);Console.WriteLine( course );}}}
Course { Name = Intro to programming, Price = 35 }
If the user does not want the auto-implemented property definition, they can define the property themselves. The constructor and deconstructor then utilize the user’s property definition. The following example sets the Name
property as protected
instead of public
.
using System;namespace Educative{// create recordpublic record Course(string Name , int Price ){protected string Name { get; init; } = Name;}class positionalProperty{static void Main(string[] args){//initialize using positonal syntaxvar course = new Course("Intro to programming", 35);Console.WriteLine( course );}}}
Course { Price = 35 }
Free Resources