Wednesday, July 7, 2010

Properties of class

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 { …}

image

Using Properties:

Start with the data:

image

c.Topping = “Chocolate”;  will set the value into the data:

image

string str = c.Topping; will get the value from the data and return to str:

image

“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

image

c.Topping = "Chocolate";

image

string str = c.Topping;

image

“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?

image

Add the check in the set method as follows

image

That is all for Properties of class.

1 comments:

  1. Awesome tutorial going through Every page. Please post more Exercises. It will help beginner like me.

    ReplyDelete