What are Properties for a Class?
They are Get and Set variables (or data) methods, but use them like variables
Why use Properties?
To hide the data (private variables) and prevent user from corrupting the data
How to hide and ensure only valid data?
Use private variables and add checking in Set variables method
A property consists of two parts:
1. a private variable (private string _topping)
2. a public Property (public string Topping): with get { … } or/and set { …}
Using Properties:
Start with the data:
c.Topping = “Chocolate”; will set the value into the data:
string str = c.Topping; will get the value from the data and return to str:
“They are Get and Set variables (or data) methods, but use them like variables”
The equivalent of using properties in traditional methods is shown on the right side
c.Topping = "Chocolate";
string str = c.Topping;
“Use private variables and add checking in Set variables method” How?
If we only allows “Chocolate” and “Plain” in our data, how do we ensure?
Add the check in the set method as follows
That is all for Properties of class.
Awesome tutorial going through Every page. Please post more Exercises. It will help beginner like me.
ReplyDelete