OOP Classes
OOP Classes
Short theory
Class Members - Fields
Bad Practice: It is a bad practice to expose fields (make them public (or internal)
= make them accessible everywhere or everywhere within the module).
It is violates the Encapsulation OOP-principle in the following aspects:
- No Abstraction - Public fields expose the internal implementation details,
breaking this abstraction.
- Limited Flexibility - Directly exposing fields limits your ability to evolve the
class without breaking existing code.
- No Compatibility with Interfaces - Interfaces in C# cannot have fields
Class Members - Fields
Instead of using Get and Set methods – we can use built-in feature in C# which is a syntactic sugar for those methods –
it’s called ”properties”
Equivalents to
Class Members - Properties
Good practice: If you don’t have any other logic that should be performed in the getter and setter in properties – then
we can simplify it to the following short form:
Or like this:
Good practice: If your properties will not be changed in any other code and will be initialized immediately after creating
the new instance of class – you should use “init” instead of “set”. This feature available since C# 9.0 (2020).
Works:
Class Members – Constructors
Constructors similar to methods can be overloaded – they have the same name but different set of parameters.
Constructors can be private. They will be useful for example when we need to have only single instance of our class (singleton pattern).
Use cases: For example we have the class that manages the database connection. We should instantiate the connection only once and
prevent doing this more times.
le ak
r y
e mo ssible
s to m of po
d t
Lea to a lo ctions
e
due conn
Class Members – Constructors
Fix: Use private constructor to avoid creating instance of class by default and delegate the instance creation to custom
static property or method. If instance is already created – this property / method will return it instead of creating a
new one (Singleton pattern).
Program stops
Class – Static classes vs Common classes
Program stops
Class – Static constructor
Static constructors are executed when any class member of class is called. Each class can contain only one static constructor.
Use case: If we want to initialize our logic only once during the application lifetime.
Example: We have a logger and a class that is used to handle logger logic. We want our logger to be configured only once.
Class – Static constructor
If we make our class static – static constructor will be executed when the “Error” method is called