Properties
Java ke ulat (jo convention se plain getter/setter methods use karta hai) ya Python ke ulat (jo @property decorator use karta hai), C# mein properties ek real language feature hain. { get; set; } bina kisi body ke — ek auto-property — aapke liye automatically ek hidden backing field generate kar deta hai, aur aap bahar se isse exactly ek public field jaisa use karte ho.
using System;
class Person {
public string Name { get; set; }
public int Age { get; set; }
}
class Program {
static void Main() {
var p = new Person();
p.Name = "Alice";
p.Age = 30;
Console.WriteLine(p.Name + " is " + p.Age);
}
}Alice is 30
Real logic ke saath full properties
Ek property ke get aur set ka ek real body bhi ho sakta hai, apne khud ke private field ke saath backed — ye useful hai jab property ko apna value compute karna ho ya jo assign ho raha hai use validate karna ho. set block ke andar value jo bhi assign hua uska implicit naam hota hai.
using System;
class Temperature {
private double celsius;
public double Celsius {
get { return celsius; }
set { celsius = value; }
}
public double Fahrenheit {
get { return celsius * 9.0 / 5.0 + 32.0; }
}
}
class Program {
static void Main() {
var t = new Temperature();
t.Celsius = 100;
Console.WriteLine(t.Fahrenheit);
}
}212
Yahan Fahrenheit ka koi set hi nahi hai — ye ek computed, read-only property hai. Aage: encapsulation — kisi property ke access modifiers use karke class ke apne invariants protect karna, aur wo real compiler error jo us promise ko todne se milta hai.
Practice exercise
Ek class Person define karo jiske auto-properties Name (string) aur Age (int) hon. Ek Person banao, Name ko "Alice" aur Age ko 30 set karo, phir dono print karo.