#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();
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: