#538 – Implement a Generic Method

In addition to classes, structs and interfaces, a method can also be generic.  A generic method is one that is declared with type parameters.  A generic method can be either a static method or an instance method.

In the example below, notice that both methods are generic, though the Dog class itself is not generic.

    public class Dog
        // Generic static method
        public static void DogBuriesThing<T>(Dog d, T thing)
            Console.WriteLine(string.Format("{0} is burying: {1}", d.Name, thing.ToString()));

        // Generic instance method
        public void BuryThing<T>(T thing)
            Console.WriteLine(string.Format("{0} is burying: {1}", Name, thing.ToString()));

Examples of calling these methods:

            // Call generic static method
            Dog buster = new Dog("Buster", 5);
            Dog.DogBuriesThing<Bone>(buster, new Bone("Buster's rawhide"));

            // Call generic instance method
            buster.BuryThing<Cow>(new Cow("Bessie"));