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

Properties vs fields in C Sharp (C#) - Hands-On Comparison

Choose your learning style9 modes available
Properties vs fields
📖 Scenario: Imagine you are creating a simple program to manage a book's information. You want to store the book's title and control how it is accessed and changed.
🎯 Goal: You will create a class with a field and a property, then see how to use them to get and set the book's title.
📋 What You'll Learn
Create a class called Book with a private field called _title of type string
Add a public property called Title with get and set accessors to control access to _title
Create an instance of Book and set the Title property
Print the value of the Title property
💡 Why This Matters
🌍 Real World
Properties help control how data inside objects is accessed and changed, which is important for keeping data safe and consistent in real programs.
💼 Career
Understanding properties and fields is essential for writing clean, maintainable code in C# and many other object-oriented languages.
Progress0 / 4 steps
1
Create the Book class with a private field
Create a class called Book with a private field named _title of type string.
C Sharp (C#)
Need a hint?

Use private string _title; inside the class to create the field.

2
Add a public property to access the field
Inside the Book class, add a public property called Title with get and set accessors that read from and write to the private field _title.
C Sharp (C#)
Need a hint?

The property should have a get that returns _title and a set that assigns value to _title.

3
Create a Book object and set the Title property
Create an instance of the Book class named myBook and set its Title property to "C# Basics".
C Sharp (C#)
Need a hint?

Use new Book() to create the object and assign the title with myBook.Title = "C# Basics";.

4
Print the Title property value
Write a line to print the value of myBook.Title to the console.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(myBook.Title); inside the Main method to print the title.