It is good practice to keep our fields private but so far we had to create at least two methods to access or change their values.


Why not star using properties? You consume properties as fields and write them (almost) as methods.

Simple property example:


But why stop there we can add more functionality to our properties, like set our string name to Upercase, return default value or check if integer is a positive number.


A property that has both accessors is read-write property. Properties with only get accessor are called read-only properties, properties with only get accessor are called write-only properties.


When you only need basic property without any additional logic, you could create auto-implemented property without filed (actually compiler creates one for you).

Simple isn’t it 🙂

Encapsulation example

In our encapsulation example we will create 3 classes:



And Manufacturer


In color Class there will be 2 private read-only fields containing colors and two public methods to access them. Fields will be private read-only because we do not want someone to access or change their values, and methods will be public because we want to access values from our fields.


Car class will also contain 2 private fields but with car model names and two public methods which can access our fields, but we will also create two public static integers whose values we will access and alter in Manufacturer class.


Manufacturer class will access methods from Color and Car classes and alter one of static integers from Car class.

Encapsulation example:





Encapsulation is one of main four object-oriented programming concepts. Encapsulation is part of OOP where we decide on which depth level another user (programmer) can can dig in our code. Encapsulation is implemented by using access modifiers.

List of access modifiers:

  • Public
  • Private
  • Protected
  • Internal
  • Protected internal

Public access modifier allows a class to expose its variables and methods to other classes/methods/objects/etc.. inside and and outside of it’s original class even outside of original assembly.

Private access modifier is default access modifier, meaning if we do not specify access modifier explicitly private is set as default one. Only methods of the same class can access its private members, meaning an instance of a class cannot access its private members L.

Protected and Protected internal access modifier are mostly used in implementing inheritance (one of the pillars of OOP). They allow child class to access variables and methods of base class. These access modifier will be explained later in Inheritance chapter.

Internal access modifier, same as public but is limited only to its root assembly. Internal is default access modifier of classes.

© 2021 LearnC#WithDarko

Theme by Anders NorenUp ↑