#1,136 – Overloading a Generic Method

In the same way that you can overload a generic class, you can overload a generic method, defining multiple generic methods having the same name but different type parameters.  You can also define non-generic methods with the same name.

Below, we overload the Dog.Bury method, defining several non-generic and several generic methods.

    public class Dog
        public string Name { get; set; }

        public Dog(string name)
            Name = name;

        public void Bury(Bone b)
            Console.WriteLine("{0} is burying: {1}", Name, b);

        public void Bury(Lawyer l)
            Console.WriteLine("{0} is burying: {1}", Name, l);

        public void Bury<T>(T thing)
            Console.WriteLine("{0} is burying: {1}", Name, thing);

        public void Bury<T>(T thing, string msg)
            Console.WriteLine("{0} : {1}", msg, thing);

        public void Bury<T1, T2>(T1 thing1, T2 thing2)
            Console.WriteLine("{0} is burying: {1}", Name, thing1);
            Console.WriteLine("{0} is burying: {1}", Name, thing2);

We can call these methods as follows:

            Dog fido = new Dog("Fido");

            fido.Bury(new Bone());
            fido.Bury(new Lawyer());
            fido.Bury<Cow>(new Cow("Bessie"));
            fido.Bury<Lawyer>(new Lawyer(), "One less lawyer");
            fido.Bury<Cow,Cat>(new Cow("Bessie"), new Cat("Puffy"));

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #1,136 – Overloading a Generic Method

  1. Pingback: Dew Drop – July 11, 2014 (#1812) | Morning Dew

  2. Pingback: Destroy Programmer Productivity - The Daily Six Pack

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: