#1,137 – Generic Methods in Non-Generic Classes

A non-generic class can contain both generic and non-generic methods.

    // Non-generic class
    public class Dog
        public string Name { get; set; }

        public Dog(string name)
            Name = name;

        // Non-generic method
        public void Bark()

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

A generic class can also contain both generic and non-generic methods.

  • Generic methods are methods that introduce a type parameter not present in the generic class
  • Both generic and non-generic methods can make use of the generic class’ type parameters
    // Generic class
    public class Pile<T>
        List<T> pile = new List<T>();

        // Non-generic method
        public void Add(T item)

        // Generic method (introduces T2)
        public void AddWithOtherThing<T2>(T item, T2 otherThing)
            Console.WriteLine("Other thing is {0}", otherThing);

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

One Response to #1,137 – Generic Methods in Non-Generic Classes

  1. Pingback: Dew Drop – July 14, 2014 (#1813) | Morning Dew

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: