0
0
C Sharp (C#)programming~20 mins

Init-only setters in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Init-Only Setters in C#
📖 Scenario: You are creating a simple program to store information about a book. Once the book's details are set, they should not be changed later.
🎯 Goal: Build a C# class Book with properties that can only be set during object creation using init-only setters. Then create an instance of Book and display its details.
📋 What You'll Learn
Create a class called Book with three properties: Title, Author, and Year.
Use init accessors for all three properties.
Create an instance of Book with the title "The Great Gatsby", author "F. Scott Fitzgerald", and year 1925.
Print the book details in the format: "Title: The Great Gatsby, Author: F. Scott Fitzgerald, Year: 1925".
💡 Why This Matters
🌍 Real World
Init-only setters are useful when you want to create objects that are immutable after creation, such as configuration settings, data transfer objects, or domain models.
💼 Career
Understanding init-only setters helps you write safer and more predictable C# code, which is valuable in professional software development to avoid bugs caused by unintended changes.
Progress0 / 4 steps
1
Create the Book class with properties
Create a class called Book with three public properties: Title (string), Author (string), and Year (int). Use auto-properties with get and init accessors for each property.
C Sharp (C#)
Need a hint?

Use public string Title { get; init; } to create a property with an init-only setter.

2
Create an instance of Book with init-only setters
Create a variable called myBook and assign it a new Book object. Set the Title to "The Great Gatsby", Author to "F. Scott Fitzgerald", and Year to 1925 using object initializer syntax.
C Sharp (C#)
Need a hint?

Use new Book { Title = "The Great Gatsby", Author = "F. Scott Fitzgerald", Year = 1925 } to create the object.

3
Try to change a property after initialization (optional test)
Add a line after creating myBook that tries to set myBook.Title to "New Title". This should cause a compile-time error because the setter is init-only. Comment out this line to keep the program running.
C Sharp (C#)
Need a hint?

Init-only setters prevent changes after object creation. Comment out the line to avoid errors.

4
Print the book details
Write a Console.WriteLine statement to print the book details in this exact format: "Title: The Great Gatsby, Author: F. Scott Fitzgerald, Year: 1925" using the myBook properties.
C Sharp (C#)
Need a hint?

Use Console.WriteLine($"Title: {myBook.Title}, Author: {myBook.Author}, Year: {myBook.Year}") to print the details.