Properties
Java ke bar-aks (jo convention se plain getter/setter methods use karta hai) ya Python ke bar-aks (jo @property decorator use karta hai), C# mein properties ek real language feature hain. { get; set; } bina kisi body ke — ek auto-property — aap ke liye khud ba khud ek hidden backing field generate kar deta hai, aur aap bahar se ise bilkul ek public field jaisa istemal karte hain.
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 Sath Full Properties
Ek property ke get aur set ka ek real body bhi ho sakta hai, apne khud ke private field ke sath 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 us ka 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 ka istemal kar ke class ke apne invariants protect karna, aur wo real compiler error jo us promise ko torne se milta hai.
Practice exercise
Ek class Person define karein jis ke auto-properties Name (string) aur Age (int) hon. Ek Person banayein, Name ko "Alice" aur Age ko 30 set karein, phir dono print karein.