Challenge - 5 Problems
Encapsulation Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing private field directly
What will be the output of this C# code when trying to access a private field directly?
C Sharp (C#)
using System; class BankAccount { private decimal balance = 1000m; } class Program { static void Main() { BankAccount account = new BankAccount(); Console.WriteLine(account.balance); Console.WriteLine("Accessing balance directly"); } }
Attempts:
2 left
💡 Hint
Private fields cannot be accessed outside their class.
✗ Incorrect
The private field 'balance' is not accessible outside the BankAccount class, so trying to access it directly causes a compilation error.
❓ Predict Output
intermediate2:00remaining
Output of using public property to access private field
What will be the output of this C# code that uses a public property to access a private field?
C Sharp (C#)
using System; class BankAccount { private decimal balance = 1000m; public decimal Balance { get { return balance; } } } class Program { static void Main() { BankAccount account = new BankAccount(); Console.WriteLine(account.Balance); } }
Attempts:
2 left
💡 Hint
Public properties can expose private fields safely.
✗ Incorrect
The public property Balance allows read-only access to the private field balance, so the output is 1000.
🧠 Conceptual
advanced2:00remaining
Why encapsulation improves code safety
Which of the following best explains why encapsulation improves code safety in object-oriented programming?
Attempts:
2 left
💡 Hint
Think about how hiding details helps protect data.
✗ Incorrect
Encapsulation hides internal details and exposes only what is necessary, which prevents accidental or harmful changes to data.
🔧 Debug
advanced2:00remaining
Identify the encapsulation violation
Which option shows a violation of encapsulation principles in C#?
C Sharp (C#)
class Person { public string name; private int age; }
Attempts:
2 left
💡 Hint
Encapsulation means hiding data from outside code.
✗ Incorrect
Making 'name' public breaks encapsulation because external code can change it without control.
🚀 Application
expert2:00remaining
Result of modifying private field via method
What will be the output of this C# program that modifies a private field using a public method?
C Sharp (C#)
using System; class Counter { private int count = 0; public void Increment() { count++; } public int GetCount() { return count; } } class Program { static void Main() { Counter c = new Counter(); c.Increment(); c.Increment(); Console.WriteLine(c.GetCount()); } }
Attempts:
2 left
💡 Hint
Methods can safely modify private data inside the class.
✗ Incorrect
The Increment method increases the private count field twice, so GetCount returns 2.