#232 – Declaring and Using Instance Methods in a Class

In a class, an instance method is a kind of class member that is a block of statements that will execute when a user of the class calls the method.  It typically acts upon the data stored in that particular instance of the class.

A method has a return value that allows the method to return a result, or a return type of void, indicating that it doesn’t return any result.

Here’s a simple example of a method:

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

        public void BarkYourAge()
        {
            for (int i = 1; i <= Age; i++)
                Console.WriteLine("Woof");
        }
    }

Calling our method:

    Dog rover = new Dog();
    rover.Name = "Rover";
    rover.Age = 3;

    rover.BarkYourAge();

The result:

Advertisement