Properties क्या हैं
Properties किसी object के data में guarded windows हैं: आप एक value देख या बदल सकते हैं, और class पहले change जांच सकती है। यह office के requests handle करने वाले एक receptionist जैसा है।
In this page:
Syntax
class ClassName
{
public type AutoProperty { get; set; }
private type field;
public type PropertyName
{
get { return field; }
set { field = value; }
}
}
Properties
Properties get और set accessors के ज़रिए किसी class का data उजागर करती हैं, आपको control देते हुए कि कोई field कैसे पढ़ा या लिखा जाए जबकि callers के लिए अब भी एक साधारण field जैसी दिखती हैं।
Auto-implemented properties ({ get; set; }) साधारण cases के लिए backing field को पूरी तरह छोड़ देते हैं। Properties manual getter/setter methods लिखने का idiomatic C# विकल्प हैं।
Note:
किसी property को publicly readable लेकिन सिर्फ class के अंदर से settable बनाने के लिए
{ get; private set; } उपयोग करें।उदाहरण: Properties
using System;
class Product
{
public string Name { get; set; }
private decimal price;
public decimal Price
{
get { return price; }
set { price = value < 0 ? 0 : value; }
}
}
class Program
{
static void Main(string[] args)
{
Product p = new Product { Name = "Pen", Price = -5 };
Console.WriteLine($"{p.Name}: {p.Price}");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- ऐसी property लिखना जिसका setter खुद को call करे, जैसे
set { Name = value; }, infinite recursion का कारण बनते हुए। - वहां public field उपयोग करना जहां validation वाली property चाहिए।
getयाsetभूल जाना और फिर property न पढ़ पाना या न लिख पाना।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: