Discover advanced Object-Oriented Programming techniques in C# with our comprehensive Part 2 guide. Master inheritance, polymorphism, encapsulation, and more. Learn to create robust classes, utilize interfaces, and leverage abstract classes for efficient code design.
Before reading this article, please go through the following article.
Properties play a vital role in Object Oriented Programming. They allow us to access the private variables of a class from outside the class. It is good to use a private variable in a class. Properties look like a combination of variables and methods. Properties have sections: "a get and a set" method. The get method should return the variable, while the set method should assign a value to it.
Step 1. Open a new project with the name "LearnProperties" as in the following.
Step 2. Now to add the new classes to the project use "Project" -> "Add class" with the class name "BikeColor" as in the following.
Step 3. After adding the new class your codes look like the following.
Step 4. Insert the following code in the class BikeColor as in the following.
Step 5. Insert the following code in the Main Module. After adding the following code it will show the error.
This is because you are accessing the private variable from outside the class; that is not allowed in OOP.
Press F5. It will show the following error.
Step 6. Now we will try to access the private variable using the property _MyBikeColor. Then it will work fine.
After creating this simple example we have learned the importance of properties in OOP. Properties help us to access the private variable of the class. Moreover, properties help us to protect the private variable of the class from unauthorized access.
Coding Principles