#354 – Correct Overloaded Method Is Automatically Called

When you have several overloaded methods in a class, the compiler will call the correct method, based on the type of the arguments passed to the method.

When you overload a method, you define several methods in a class with the same name, but different parameters.

    public class Dog
    {
        // General bark
        public void Bark()
        {
            Console.WriteLine("Woof");
        }

        // Specific bark
        public void Bark(string barkSound)
        {
            Console.WriteLine(barkSound);
        }

        // Repeated barking
        public void Bark(int numBarks)
        {
            for (int i = 1; i <= numBarks; i++)
                Console.WriteLine("Woof #{0}", i);
        }
    }

The compiler will automatically figure out which method to call, based on the arguments that you pass in.

            Dog jack = new Dog("Jack", 15);

            jack.Bark();           // General bark
            jack.Bark(5);          // Repeated barking
            jack.Bark("Rowwwwf");  // Specific bark
Advertisements