#237 – Referencing Class Fields from Within One of its Methods

In any of the instance methods for a class, you can reference one of that class’ fields by just using the field name.  The value used will be the value stored in that field, for the object (instance of the class) that was used to invoke the method.

In the example below, we have Name and Age fields in the class.  The PrintNameAndAge method can just reference these fields by name to get their value for the current object.

    public class Dog
    {
        public string Name;
        public int Age;

        public void PrintNameAndAge()
        {
            Console.WriteLine("{0} is {1} yrs old", Name, Age);
        }
    }

We might call this method as follows:

            Dog kirby = new Dog();
            kirby.Name = "Kirby";
            kirby.Age = 15;

            // Prints "Kirby is 15 yrs old"
            kirby.PrintNameAndAge();

#231 – Declaring and Using Instance Fields in a Class

In a class, an instance field is a kind of class member that is a variable declared in the class and having a particular type.  There is one copy of the field for each instance of the class.  You can read and write the value of the field using a reference to the instance of the class.

Fields are declared in a class as follows:

    public class Dog
    {
        public string Name;
        public int Age;
    }

These fields can then be used as follows:

            Dog buster = new Dog();  // Create new instance of Dog
            buster.Name = "Buster";  // Write to Name field
            buster.Age = 3;          // Write to Age field

            Dog kirby = new Dog();   // Another instance of a Dog
            kirby.Name = "Kirby";
            kirby.Age = 13;

            // Reading properties
            int agesAdded = buster.Age + kirby.Age;