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

Access Modifiers की जानकारी

Access modifiers तय करते हैं कि कौन किसी चीज़ का उपयोग कर सकता है, जैसे अलग-अलग locks वाले घर के कमरे। Public सबके लिए खुला है, private सिर्फ class के लिए है।

In this page:

  1. Access Modifiers
Syntax
csharp
class ClassName
{
    public type A;      // anywhere
    private type B;     // this class only
    protected type C;   // this class and derived classes
    internal type D;    // this assembly
}

Access Modifiers

Access modifiers (public, private, protected, internal) नियंत्रित करते हैं कि कौन सा code किसी class member को देख सकता है।

public members हर जगह दिखाई देते हैं, private members सिर्फ declaring class के अंदर, और protected members class और इसकी subclasses के अंदर। fields को private के रूप में encapsulate करना और public properties के ज़रिए उजागर करना एक core OOP practice है।

Warning: C# में अगर आप एक modifier छोड़ दें तो class members default रूप से private हैं।

उदाहरण: Access Modifiers

markup
using System;

class Account
{
    private decimal balance;

    public Account(decimal startingBalance)
    {
        balance = startingBalance;
    }

    public void Deposit(decimal amount)
    {
        balance += amount;
    }

    public decimal GetBalance()
    {
        return balance;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Account acc = new Account(100);
        acc.Deposit(50);
        Console.WriteLine(acc.GetBalance());
    }
}
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. members को default private access के साथ छोड़ना और 'inaccessible due to its protection level' errors पाना।
  2. हर member को public बनाना, जो encapsulation तोड़ता है।
  3. protected उपयोग करना और असंबंधित classes से access की उम्मीद करना।
🔒

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.