Learn Object Oriented Programming Using C#: Part 2

Before reading this article, please go through the following article:

  1. Learn Object Oriented Programming using C#: Part 1

Introduction to C# Class Properties

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:

Class1.jpg

Step 2

Now to add the new classes to the project use "Project" -> "Add class" with the class name "BikeColor" as in the following:

Class2.jpg
.
Step 3

After adding the new class your codes looks like the following:

Class3.jpg

Step 4

Insert the following code in the class BikeColor as in the following:

Class4.jpg

Step 5

Insert the following code in the Main Module. After adding the following code it will show the error.

Class5.jpg

This is because you are accessing the private variable from outside the class; that is not allowed in OOP.

Class6.jpg

Press F5. It will show the following error.

Class7.jpg

Step 6

Now we will try to access the private variable using the property _MyBikeColor. Then it will work fine.

Class8.jpg

Class9.jpg

Conclusion

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 the unauthorized access.

Up Next
    Ebook Download
    View all
    Learn
    View all