Introduction to Objects and Classes in C# - Properties and Variables
(Page 5 of 9 )
Variables declared in a class store the data for each instance. What does this mean? It means that when you instantiate this class (that is, when you create an object of this class) the object will allocate memory locations to store the data of its variables. Let's take an example to understand it well.
class Person
{
public int Age;
public string HairColor;
}
This is our simple class which contains 2 variables. Don't worry about public keyword now because we will talk about it later. Now we will instantiate this class (that is, when you create an object of this class).
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();
}
So we begin our Main method by creating 2 objects of type Person. After creating the 2 objects we initialize the instance variables for object Michael and then for object Mary. Finally we print some values to the console. Here, when you create the Michael object, the C# compiler allocates a memory location for the 2 instance variables to put the values there. Also, the same thing with the Mary object; the compiler will create 2 variables in memory for Mary object. So each object now contains different data. Note that we directly accessed the variables and we put any values we wanted, right? But wait there is a solution to this problem. We will use properties.
Next: Properties >>
More C# Articles
More By Michael Youssef