Encapsulation
A property's get and set can each have their own access modifier. public double Balance { get; private set; } means anyone can read Balance, but only code inside BankAccount itself can assign to it — external code has to go through a method like Deposit, which the class controls completely.
using System;
class BankAccount {
public double Balance { get; private set; }
public BankAccount(double initial) {
Balance = initial;
}
public void Deposit(double amount) {
Balance += amount;
}
}
class Program {
static void Main() {
var account = new BankAccount(100);
account.Deposit(50);
Console.WriteLine(account.Balance);
}
}150
What the real compiler error looks like
Trying to assign to a private set from outside the class isn't just bad style — it's a compile error. This is genuinely what the compiler reports — captured from a real run, not written to look plausible:
using System;
class Person {
public string Name { get; private set; }
public Person(string name) { Name = name; }
}
class Program {
static void Main() {
var p = new Person("Alice");
p.Name = "Bob";
Console.WriteLine(p.Name);
}
}Main.cs(11,11): error CS0272: The property or indexer `Person.Name' cannot be used in this context because the set accessor is inaccessible Main.cs(4,39): (Location of the symbol related to previous error) Compilation failed: 1 error(s), 0 warnings
Next: inheritance — base classes, the base keyword, and overriding a method with virtual and override.
Practice exercise
Define a class BankAccount with a property Balance that has a private set, a constructor that sets an initial balance, and a Deposit(double amount) method that adds to Balance. Create one with 100, deposit 25, then print Balance.