Lesson Weekend

So far, we’ve used the public keyword throughout our programs. However, it's not a good idea to make all fields public. Let's learn the proper way to handle fields on a custom class. In this lesson, we'll discuss best practices for access level modifiers.

Access Level Modifiers

Let's revisit our car dealership application. Currently, all class fields have been declared public:

public class Car
  public string MakeModel;
  public int Price;
  public int Miles;


The public keyword is an access level modifier. It determines who or what may access a field or method. Unfortunately, making fields public isn't very secure or scalable. It means any method anywhere could change the field of an object.

We can declare fields private instead of public, which means only code within the class can directly access these fields. Any code outside the class will not have this access. This is far more secure and considered best practice. However, it prevents us from being able to directly set or retrieve fields from outside of the class with object notation like this: testCar.Price = 1000;

This may seem awkward at first, especially since we've gotten used to this in Intro. However, it will make our code more stable and maintainable. There's also special methods we can use to alter object fields as necessary without breaking these rules. These methods are called getters and setters. We'll discuss these in a moment.

Private Access Level Modifiers

Let's make the fields of our Car class private:

public class Car
  private string MakeModel;
  private int Price;
  private int Miles;


Let's recompile and run the program.

$ dotnet run

...We'll see the following error:

Program.cs(33,38): error CS0122: `Dealership.Car.MakeModel' is inaccessible due to its protection level

This error states that the MakeModel information used in our Main() method of Program.cs is now inaccessible. This is because Car fields (including the MakeModel field Program.cs is attempting to access) are now private and cannot be accessed from outside the class. In other words, MakeModel, Price, and Miles can only be used inside the Car class declaration now. We'll fix that in the next lesson. From now on, all fields should be made private.

There are five access modifiers in C#, which include protected, internal, and a combined modifier called protected internal. Read more about how they work in the C# Docs.


Access level modifier: This determines who or what may access a field or method.

Getter: A method to allow read access to a field.

private: Access limited to within a class.

public: Allows access throughout an application.

Setter: A method to allow write access to a field.

Lesson 5 of 10
Last updated more than 3 months ago.