#1,136 – Overloading a Generic Method
July 11, 2014 2 Comments
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"));
Pingback: Dew Drop – July 11, 2014 (#1812) | Morning Dew
Pingback: Destroy Programmer Productivity - The Daily Six Pack