#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"