Learn Object Oriented Programming Using C#: Part 2

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

  1. Object Oriented Programming Using C#: Part 1
  2. Object Oriented Programming Using C#: Part 3
  3. Object Oriented Programming Using C#: Part 4
  4. Object Oriented Programming Using C#: Part 5
  5. Object Oriented Programming Using C#: Part 6
  6. Object Oriented Programming Using C#: Part 7
  7. Object Oriented Programming Using C#: Part 8
  8. Object Oriented Programming Using C#: Part 9
  9. Object Oriented Programming Using C#: Part 10

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:

C# Class Properties

Step 2

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

C# Class Properties
.
Step 3

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

C# Class Properties

Step 4

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

C# Class Properties

Step 5

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

C# Class Properties

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

C# Class Properties

Press F5. It will show the following error.

C# Class Properties

Step 6

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

C# Class Properties

C# Class Properties

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.


Recommended Ebook

Introduction to C# 8

Download Now!
Similar Articles