C# Access Modifiers

C# Access Modifiers

By now, you have probably noticed the public keyword used in our previous examples.

In C#, public is an access modifier. Access modifiers are used to set the visibility level (or access level) for classes, fields, methods, and properties. They control which parts of your code can "see" and interact with other parts.


Types of Access Modifiers

C# offers several access modifiers, but the most common ones you need to know are:

Modifier Description
public The code is accessible for all classes. There are no restrictions.
private The code is accessible only within the same class. This is the default modifier if you don't specify one.
protected The code is accessible within the same class, or in a class that is inherited from that class.
internal The code is only accessible within its own assembly (the compiled .exe or .dll file).

The private Modifier

If you declare a field as private, it cannot be accessed from outside the class. If you try to do so, C# will throw an error.

Example: Private Access

class Car 
{
  // private by default, but you can explicitly write 'private'
  private string model = "Mustang"; 
}

class Program { static void Main(string[] args) { Car myObj = new Car(); // ERROR: 'Car.model' is inaccessible due to its protection level // Console.WriteLine(myObj.model); } }


The public Modifier

If you declare a field as public, it can be accessed from anywhere, including from different classes!

Example: Public Access

using System;

class Car { public string model = "Mustang"; }

class Program { static void Main(string[] args) { Car myObj = new Car(); // This works perfectly! Console.WriteLine(myObj.model); } }

Why Use Access Modifiers?

You might wonder, "Why not just make everything public?"

The primary reason is Security. By keeping fields private, you prevent outside classes from messing with data they shouldn't touch. This concept is known as Encapsulation, which ensures that sensitive data is hidden from users. We will learn how to safely expose private data using Properties in the next lesson!

Note: By default, all members of a class are private if you don't specify an access modifier.


Exercise

?

Which access modifier restricts access to only within the same class?