Introduction to Objects and Classes in C# - Reworked (Page 7 of 9 )
static void Main(string[] args) { Person Michael = new Person(); Person Mary = new Person();
// Specify some values for the instance variables Michael.Age = 20; Michael.HairColor = "Brown"; Mary.Age = 25; Mary.HairColor = "Black";
// print the console's screen some of the variable's values Console.WriteLine("Michael's age = {0}, and Mary's age = {1}",Michael.Age, Mary.Age); Console.ReadLine(); }
Here I created the same objects from the last example, except that I used only properties to access the variable instead of accessing it directly. Look at the following line of code
Michael.Age = 20;
When you assign a value to the property like that C# will use the set accessor. The great thing with the set accessor is that we can control the assigned value and test it; and maybe change to in some cases. When you assign a value to a property C# changes the value in a variable and you can access the variable's value using the reserved keyword value exactly as I did in the example. Let's see it again here.
set { if(value <= 65 && value >= 18) { age = value; } else age = 18; }
Here in the code I used if statement to test the assigned value because for some reason I want any object of type Person to be aged between 18 and 65. Here I test the value and if it is in the range then I will simply store it in the variable age. If it's not in the range I will put 18 as a value to age.