0
0
C Sharp (C#)programming~5 mins

Access modifiers (public, private, internal) in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Access modifiers control who can use parts of your code. They help keep your code safe and organized.

When you want everyone to use a class or method, make it public.
When you want only the current class to use a method or variable, make it private.
When you want to share code only inside the same project or assembly, use internal.
Syntax
C Sharp (C#)
public class MyClass {
    public int number;      // accessible everywhere
    private int secret;    // accessible only inside MyClass
    internal int shared;   // accessible inside the same assembly
}

public means anyone can access.

private means only the current class can access.

internal means only code in the same project or assembly can access.

Examples
This class shows all three access levels on different fields.
C Sharp (C#)
public class Car {
    public string Make;      // anyone can see
    private string Model;    // only inside Car
    internal int Year;       // inside same project
}
Private balance hides the money amount. Public methods let others add money or check balance safely.
C Sharp (C#)
public class BankAccount {
    private decimal balance;

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

    public decimal GetBalance() {
        return balance;
    }
}
Sample Program

This program shows how public, private, and internal control access to Person's data.

C Sharp (C#)
using System;

public class Person {
    public string Name;          // anyone can access
    private int age;             // only inside Person
    internal string City;        // inside same assembly

    public Person(string name, int age, string city) {
        Name = name;
        this.age = age;
        City = city;
    }

    public void ShowAge() {
        Console.WriteLine($"Age is {age}");
    }
}

class Program {
    static void Main() {
        Person p = new Person("Alice", 30, "New York");
        Console.WriteLine(p.Name);      // works
        // Console.WriteLine(p.age);    // error: age is private
        p.ShowAge();                   // works, prints age
        Console.WriteLine(p.City);      // works inside same assembly
    }
}
OutputSuccess
Important Notes

Private members cannot be accessed outside their own class.

Internal members are accessible only within the same project or assembly.

Public members are accessible from anywhere.

Summary

Access modifiers control who can use your code parts.

Use public for open access, private for hiding inside a class, and internal for sharing inside a project.