Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#

What are init only setters in C# 9.0?

Ayesha Naeem

Init only setters in C# 9.0 provide a method to initialize object members.

C# 9.0 allows the user to create init accessors instead of set accessors. init accessors allow the members of an instance of the object to be set only at the time of the construction. Once the construction of the instance is complete, the members become immutable.

However, the set accessor allows the members to be changed even after the initialization is complete.

init can be declared on members of any object and callers can use property initializers to set the members at the time of the creation of an object.

Example

The following example demonstrates how to use init only setters.

  • The program creates an object Student, and declares two of its members with init and the third member lastName with set.
  • In main, the program creates an instance of the object and initializes the first two members in the construction.
  • Notice that the program can set the third member even after the initialization, because the third member is mutable and declared with the set accessor.
using System;
namespace c9 {

    // create an object

    public class Student {

    // replace set with init
    public int Id {get; init;} 
    public string firstName { get;init;}
    public string lastName { get;set;}
    }   
    class Program {
        static void Main(string[] args) {
            Student studentOne = new Student{Id = 1, firstName = "Sam"};
             
            // set the last name after initialization 
            
            studentOne.lastName = "Carlos";

            //display properties

            Console.WriteLine("ID : " + studentOne.Id);

            Console.WriteLine("Name : " + studentOne.firstName);

            Console.WriteLine("Last Name : " + studentOne.lastName);

            
        }
    }
}

Output

ID : 1

Name : Sam

Last Name : Carlos

RELATED TAGS

c#

CONTRIBUTOR

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

View all Courses

Keep Exploring