C# Access Modifiers

By now, you're familiar with a public keyword from many of our examples:

public string color;
        

A public keyword is an access modifier, which is used to set the level of accessibility / visibility of classes, fields, paths and properties.

C# has the following access modifiers:

Modifier Description
public The code is accessible for all classes
private The code is only accessible within the same class
protected The code is accessible within the same class, or in a class that is inherited from that class. You will learn more about inheritance in a later chapter
internal The code is only accessible within its own assembly, but not from another assembly. You will learn more about this in a later chapter

There's also two combinations: protected internal and private protected.

For now, lets focus on public and private modifiers.


Private Modifier

If you are announcing a field with a private access controller, it can only be accessed in the same category:

Example
class Car
            {
              private string model = "Mustang";
            
              static void Main(string[] args)
              {
                Car myObj = new Car();
                Console.WriteLine(myObj.model);
              }
            }

If you try to access it outside the classroom, an error will occur:

Example
class Car
            {
              private string model = "Mustang";
            }
            
            class Program
            {
              static void Main(string[] args)
              {
                Car myObj = new Car();
                Console.WriteLine(myObj.model);
              }
            }
            

Public Modifier

When you announce a field with a public access adapter, it is accessible to all classes:

Example
class Car
            {
              public string model = "Mustang";
            }
            
            class Program
            {
              static void Main(string[] args)
              {
                Car myObj = new Car();
                Console.WriteLine(myObj.model);
              }
            }
            

Note: By default, all class members are private if you do not specify access control:

Example
class Car
            {
              string model;  // private
              string year;   // private
            }