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
EasyLet'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 aUserProfileclass in theSecuritynamespace that manages user information with appropriate access levels. The profile should have:- A
publicpropertyUsername(string) - anyone can see the username - A
privatefieldpassword(string) - only the class itself should access this - A
protectedfieldemail(string) - the class and its children can access this - An
internalfielduserId(int) - accessible within the same assembly
publicmethod calledGetPublicInfo()that returns"User: {Username}". Add anotherpublicmethod calledValidatePassword(string input)that returnstrueif the input matches the private password,falseotherwise.- A
AdminProfile.cs: Create anAdminProfileclass in theSecuritynamespace that inherits fromUserProfile. This class demonstrates howprotectedmembers become accessible in derived classes. The constructor should accept the same four parameters and pass them to the base constructor. Add apublicmethod calledGetAdminInfo()that returns"Admin: {Username}, Email: {email}"- notice you can access the protectedemailfield here!Program.cs: In your main file, create aUserProfileand anAdminProfileusing 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
- 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.comNotice 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()
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator3Class Architecture
Instance vs Static Data'readonly' & 'const' KeywordsBacking FieldsRecap - Bank Account Manager6Encapsulation
Access ModifiersProperties for EncapsulationData Hiding ImplementationImmutability PatternsRecap - Student Records