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

Get and set accessors in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Get and Set Accessors in C#
📖 Scenario: You are creating a simple program to manage a Book object. Each book has a Title and a Price. You want to control how these values are accessed and changed using get and set accessors.
🎯 Goal: Build a Book class with Title and Price properties using get and set accessors. Then create an instance of Book, set its properties, and print them.
📋 What You'll Learn
Create a class called Book with private fields for title and price.
Add public properties Title and Price with get and set accessors.
In the set accessor of Price, ensure the price cannot be set to a negative value; if negative, set it to 0.
Create an instance of Book in Main, set the Title to "C# Basics" and Price to 25.
Print the Title and Price of the book.
💡 Why This Matters
🌍 Real World
Get and set accessors are used in real programs to protect data and add rules when changing values, like preventing negative prices.
💼 Career
Understanding properties with get and set is essential for writing clean, safe, and maintainable C# code in many software development jobs.
Progress0 / 4 steps
1
Create the Book class with private fields
Create a class called Book with private fields string title and decimal price.
C Sharp (C#)
Need a hint?

Use private string title; and private decimal price; inside the class.

2
Add public properties with get and set accessors
Add public properties Title and Price to the Book class. Use get and set accessors for both. In the set accessor of Price, if the value is negative, set price to 0; otherwise, set it to the value.
C Sharp (C#)
Need a hint?

Use public string Title { get { return title; } set { title = value; } } and similar for Price with a condition in set.

3
Create a Book instance and set properties
In the Main method, create an instance of Book called myBook. Set its Title to "C# Basics" and Price to 25.
C Sharp (C#)
Need a hint?

Use Book myBook = new Book(); then set properties with myBook.Title = "C# Basics"; and myBook.Price = 25;.

4
Print the Title and Price of the book
Add Console.WriteLine statements in Main to print the Title and Price of myBook in the format: Title: C# Basics and Price: 25.
C Sharp (C#)
Need a hint?

Use Console.WriteLine($"Title: {myBook.Title}"); and Console.WriteLine($"Price: {myBook.Price}");.