#540 – Non-Generic Methods in a Generic Class

You can have both generic and non-generic methods in a generic class.  The non-generic methods can still make use of the class’ generic type parameters.

In the example below, the BuryThing method accepts a parameter whose type matches the type parameter of the class itself.

    public class Dog<T>
    {
        // Not classified as generic method because it does not introduce new type parameter
        public void BuryThing(T thing)
        {
            Console.WriteLine(string.Format("{0} is burying: {1}", Name, thing.ToString()));
        }

When we invoke this method, we must pass it an object whose type matches the type parameter that the class was constructed with.

            Dog<Cow> d = new Dog<Cow>("Buster", 5);
            d.BuryThing(new Cow("Bessie"));
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #540 – Non-Generic Methods in a Generic Class

  1. Pingback: #1,137 – Generic Methods in Non-Generic Classes | 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 )

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: