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