Introduction to Objects and Classes in C# - Properties
(Page 6 of 9 )
Properties are a way to access the variables of the class in a secure manner. Let's see the same example using properties.
class Person
{
private int age;
private string hairColor;
public int Age
{
get
{
return age;
}
set
{
if(value <= 65 && value >= 18)
{
age = value;
}
else
age = 18;
}
}
public string HairColor
{
get
{
return hairColor;
}
set
{
hairColor = value;
}
}
}
I made some modifications, but focus on the new 2 properties that I created. So the property consists of 2 accessors. The get accessor, responsible of retrieving the variable value, and the set accessor, responsible of modifying the variable's value. So the get accessor code is very simple. We just use the keyword return with the variable name to return its value. So the following code:
get
{
return hairColor;
}
returns the value stored in hairColor.
[Note]
The keyword value is a reserved keyword by C# (that is, reserved keywords means that these keywords are owned only by C# and you can't create it for any other purposes. For example, you can't create a variable called value .If you did, the C# compiler would generate an error. To make things easier, Visual Studio.NET will color the reserved keywords in blue.)
[/Note]
Let's put this code to work and then discuss the set accessor..
Next: Reworked >>
More C# Articles
More By Michael Youssef