c-sharp
  1. c-sharp-access-modifiers

C# Access Modifiers

In C#, access modifiers control the visibility and accessibility of types and members in a program. They help define the level of encapsulation and dictate which parts of the program can access certain elements. This guide covers the syntax, usage, and considerations when working with access modifiers in C#.

Syntax

// Access modifier for class
[access_modifier] class MyClass
{
    // Access modifier for member
    [access_modifier] int myField;
}

Example

// Public access modifier example
public class BankAccount
{
    // Private field can only be accessed within this class
    private decimal balance;

    // Public property allows external access to the balance
    public decimal Balance
    {
        get { return balance; }
        set { balance = value; }
    }
}

class Program
{
    static void Main()
    {
        BankAccount account = new BankAccount();
        
        // External code can access the public property
        account.Balance = 1000.0M;
        Console.WriteLine($"Account Balance: {account.Balance}");
    }
}

Output

The output will be the account balance value retrieved and displayed by the external code.

Explanation

  • The public access modifier allows the BankAccount class and its Balance property to be accessed from external code.
  • The private access modifier restricts the balance field to be accessible only within the BankAccount class.

Use

Use access modifiers in C# when:

  • You want to control the visibility of types and members.
  • Encapsulation is essential for maintaining the integrity of the program.
  • You need to expose certain members to external code while hiding the internal implementation.

Important Points

  • Common access modifiers include public, private, protected, internal, and protected internal.
  • Access modifiers apply to classes, interfaces, structs, enums, and their members.
  • private is the default access modifier for class members if no modifier is specified.

Summary

C# access modifiers are crucial for defining the visibility and accessibility of types and members within a program. They contribute to encapsulation, enabling better code organization and maintenance. By choosing the appropriate access modifiers, you can control the exposure of your program's elements and ensure a clean and maintainable codebase. Understanding how access modifiers work is fundamental to writing robust and modular C# applications.

Published on: