Encapsulation
Property ke get aur set, dono ka apna-apna access modifier ho sakta hai. public double Balance { get; private set; } ka matlab hai koi bhi Balance read kar sakta hai, lekin sirf BankAccount ke andar ka code hi usse assign kar sakta hai — bahar ka code Deposit jaise method se hi guzarna padta hai, jisko class poori tarah control karti hai.
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
Real compiler error kaisa dikhta hai
Class ke bahar se private set ko assign karne ki koshish sirf bad style nahi hai — ye ek compile error hai. Ye genuinely wahi hai jo compiler report karta hai — ek real run se capture kiya gaya, plausible dikhne ke liye likha nahi gaya:
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
Aage: inheritance — base classes, base keyword, aur virtual aur override se kisi method ko override karna.
Practice exercise
Ek class BankAccount define karo jiska property Balance ho jiska set private ho, ek constructor ho jo initial balance set kare, aur ek Deposit(double amount) method ho jo Balance mein add kare. 100 se ek banao, 25 deposit karo, phir Balance print karo.