#1,137 – Generic Methods in Non-Generic Classes
July 14, 2014 1 Comment
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() { Console.WriteLine("Woof"); } // 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) { pile.Add(item); } // Generic method (introduces T2) public void AddWithOtherThing<T2>(T item, T2 otherThing) { this.Add(T); Console.WriteLine("Other thing is {0}", otherThing); } }
Pingback: Dew Drop – July 14, 2014 (#1813) | Morning Dew