#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"));

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.

One Response to #538 – Implement a Generic Method

  1. Pingback: #1,028 – Generic Types vs. Generic Methods | 2,000 Things You Should Know About C#

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: