Menu
Coddy logo textTech

Access Modifiers

Part of the Object Oriented Programming section of Coddy's C# journey — lesson 31 of 70.

Access modifiers control who can see and use your class members. They're the foundation of encapsulation - one of OOP's core principles. By restricting access, you protect your data and create clear boundaries in your code.

C# provides four main access modifiers:

public class BankAccount
{
    public string AccountHolder;      // Accessible from anywhere
    private decimal balance;          // Only within this class
    protected string accountType;     // This class and derived classes
    internal int branchCode;          // Within the same assembly
}

public members are accessible from any code.

private members can only be accessed within the same class - this is the most restrictive and the default for class members.

protected allows access from the class itself and any class that inherits from it.

internal restricts access to code within the same assembly (project).

When no modifier is specified, class members default to private:

class Example
{
    int secret;  // private by default
}

Choosing the right access level is about exposing only what's necessary. Start with private and only increase visibility when you have a clear reason. This prevents other code from depending on implementation details you might want to change later.

challenge icon

Challenge

Easy

Let's build a secure user profile system that demonstrates how access modifiers protect sensitive data while exposing only what's necessary. You'll create a class where different pieces of information have different visibility levels based on who should be able to access them.

You'll organize your code across three files:

  • UserProfile.cs: Create a UserProfile class in the Security namespace that manages user information with appropriate access levels. The profile should have:
    • A public property Username (string) - anyone can see the username
    • A private field password (string) - only the class itself should access this
    • A protected field email (string) - the class and its children can access this
    • An internal field userId (int) - accessible within the same assembly
    Include a constructor that accepts username, password, email, and userId. Add a public method called GetPublicInfo() that returns "User: {Username}". Add another public method called ValidatePassword(string input) that returns true if the input matches the private password, false otherwise.
  • AdminProfile.cs: Create an AdminProfile class in the Security namespace that inherits from UserProfile. This class demonstrates how protected members become accessible in derived classes. The constructor should accept the same four parameters and pass them to the base constructor. Add a public method called GetAdminInfo() that returns "Admin: {Username}, Email: {email}" - notice you can access the protected email field here!
  • Program.cs: In your main file, create a UserProfile and an AdminProfile using input values. Demonstrate the access levels by calling the available public methods and accessing the internal field directly (since you're in the same assembly). Show what information each type of user can reveal.

You will receive five inputs:

  • Username
  • Password
  • Email
  • User ID (integer)
  • Password attempt to validate

Print the output in this format:

Regular User:
{GetPublicInfo() result}
Internal ID: {userId}
Password valid: {ValidatePassword result}
Admin User:
{GetAdminInfo() result}

For example, if the inputs are alice, secret123, alice@email.com, 1001, and secret123, the output should be:

Regular User:
User: alice
Internal ID: 1001
Password valid: True
Admin User:
Admin: alice, Email: alice@email.com

Notice how the password remains completely hidden - you can only validate it, never retrieve it. The email is protected, so only the AdminProfile (a derived class) can expose it. The internal userId is accessible from your main file because it's in the same assembly. This is encapsulation in action!

Cheat sheet

Access modifiers control the visibility and accessibility of class members, forming the foundation of encapsulation in OOP.

C# provides four main access modifiers:

public class BankAccount
{
    public string AccountHolder;      // Accessible from anywhere
    private decimal balance;          // Only within this class
    protected string accountType;     // This class and derived classes
    internal int branchCode;          // Within the same assembly
}

public: accessible from any code

private: only accessible within the same class (most restrictive, default for class members)

protected: accessible from the class itself and any derived classes

internal: accessible only within the same assembly (project)

When no modifier is specified, class members default to private:

class Example
{
    int secret;  // private by default
}

Best practice: start with private and only increase visibility when necessary to prevent external code from depending on implementation details.

Try it yourself

using System;
using Security;

class Program
{
    public static void Main(string[] args)
    {
        // Read inputs
        string username = Console.ReadLine();
        string password = Console.ReadLine();
        string email = Console.ReadLine();
        int userId = Convert.ToInt32(Console.ReadLine());
        string passwordAttempt = Console.ReadLine();

        // TODO: Create a UserProfile object with the input values

        // TODO: Create an AdminProfile object with the same input values

        // TODO: Print "Regular User:"

        // TODO: Print the result of GetPublicInfo()

        // TODO: Print "Internal ID: " followed by the userId field (accessible because same assembly)

        // TODO: Print "Password valid: " followed by the result of ValidatePassword()

        // TODO: Print "Admin User:"

        // TODO: Print the result of GetAdminInfo()
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming