← Back to C# Course | Chapter 6: OOP Basics | Lesson 4 of 7

Properties क्या हैं

Properties किसी object के data में guarded windows हैं: आप एक value देख या बदल सकते हैं, और class पहले change जांच सकती है। यह office के requests handle करने वाले एक receptionist जैसा है।

In this page:

  1. Properties
Syntax
csharp
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

markup
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}");
    }
}
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. #}
आम गलतियां
  1. ऐसी property लिखना जिसका setter खुद को call करे, जैसे set { Name = value; }, infinite recursion का कारण बनते हुए।
  2. वहां public field उपयोग करना जहां validation वाली property चाहिए।
  3. get या set भूल जाना और फिर property न पढ़ पाना या न लिख पाना।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.