Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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#)
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#)
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#)
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#)
Hint
Use Console.WriteLine($"Title: {myBook.Title}"); and Console.WriteLine($"Price: {myBook.Price}");.
Practice
(1/5)
1. What is the main purpose of get and set accessors in a C# class?
easy
A. To handle exceptions automatically
B. To define methods that perform calculations
C. To create variables inside a class
D. To control how a property value is read and changed
Solution
Step 1: Understand the role of accessors
Get and set accessors are used to read and write property values in a controlled way.
Step 2: Differentiate from other class members
They are not methods or variables themselves but control access to data.
Final Answer:
To control how a property value is read and changed -> Option D
Quick Check:
Get/set control property access = A [OK]
Hint: Get/set control property reading and writing [OK]
Common Mistakes:
Confusing accessors with methods
Thinking they create variables
Assuming they handle exceptions automatically
2. Which of the following is the correct syntax for an auto-implemented property with get and set accessors in C#?
easy
A. public int Age { get() set(); }
B. public int Age() { get; set; }
C. public int Age { get; set; }
D. public int Age get; set;
Solution
Step 1: Identify correct property syntax
Auto-properties use curly braces with get and set accessors separated by semicolons.
Step 2: Check each option
public int Age { get; set; } matches the correct syntax: public int Age { get; set; }
Final Answer:
public int Age { get; set; } -> Option C
Quick Check:
Auto-property syntax = C [OK]
Hint: Auto-properties use braces with get; set; inside [OK]
Common Mistakes:
Using parentheses instead of braces
Missing semicolons after get and set
Writing get and set without braces
3. What will be the output of the following C# code?
class Person {
private string name;
public string Name {
get { return name; }
set { name = value.ToUpper(); }
}
}
var p = new Person();
p.Name = "alice";
Console.WriteLine(p.Name);
medium
A. alice
B. ALICE
C. Name
D. null
Solution
Step 1: Analyze the set accessor behavior
The set accessor converts the assigned value to uppercase before storing it in the private field.
Step 2: Analyze the get accessor output
The get accessor returns the stored uppercase string.
Final Answer:
ALICE -> Option B
Quick Check:
Set converts to uppercase, output = ALICE [OK]
Hint: Set modifies value before storing, get returns stored value [OK]
Common Mistakes:
Ignoring the ToUpper() call in set
Assuming original case is preserved
Confusing field and property names
4. Identify the error in this property definition:
public int Score {
get { return score; }
set score = value; }
}
medium
A. Incorrect set accessor syntax
B. Missing semicolon after return statement
C. Missing private field declaration
D. Property name should be lowercase
Solution
Step 1: Check set accessor syntax
The set accessor must use braces { } around its code block, but here it is missing the opening brace.
Step 2: Confirm other parts
The return statement has a semicolon, private field may be declared elsewhere, and property names are PascalCase by convention.
Final Answer:
Incorrect set accessor syntax -> Option A
Quick Check:
Set accessor needs braces = A [OK]
Hint: Set accessor must have braces around code block [OK]
Common Mistakes:
Omitting braces in set accessor
Confusing property and field names
Assuming property names must be lowercase
5. You want to create a property Age that only allows values between 0 and 120. Which implementation correctly enforces this using get and set accessors?
hard
A. private int age; public int Age { get { return age; } set { if (value >= 0 && value <= 120) age = value; } }
B. public int Age { get; set; } // No validation needed
C. private int age; public int Age { get { return age; } set { age = value; } }
D. private int age; public int Age { get { return age; } set { if (value > 0) age = value; } }
Solution
Step 1: Check validation logic in set accessor
private int age; public int Age { get { return age; } set { if (value >= 0 && value <= 120) age = value; } } checks if value is between 0 and 120 before assigning it to the private field.
Step 2: Compare other options
The auto-implemented property has no validation. The simple backing field assignment lacks checks. The partial validation only checks if value > 0, missing the upper limit.
Final Answer:
private int age; public int Age { get { return age; } set { if (value >= 0 && value <= 120) age = value; } } -> Option A
Quick Check:
Set accessor validates range 0-120 = B [OK]
Hint: Use if condition in set to validate value range [OK]