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

#263 – A Method’s Signature Must Be Unique Within Its Type

You can define more than one method with the same name in a type–as long as the methods’ signatures are different.  The signature of a method is represented by its name and the number and types of its parameters.

In the example below, we define three different methods in the Dog class, all named Bark. Each method has a different input parameter, so it’s okay to define all three methods in the same class.

        public void Bark()
        {
            Console.WriteLine("Woof");
        }

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

        public void Bark(DateTime today)
        {
            Console.WriteLine("Today is {0}", today.ToString());
        }

When we call the Bark method on a Dog object, the compiler can tell based on the type of the input parameter, which of these Bark methods to call.

Defining more than one method in a class with the same name is also known as overloading the method.