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

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 )

w

Connecting to %s

%d bloggers like this: