5. Life without Generics public class ExampleStack { private object [] contents = new object [99]; private int ptr ; public void Push( object o) { contents[++ptr] = o; } public object Pop() { return contents[ptr--]; } } What can go wrong ? ExampleStack stack2 = new ExampleStack (); stack2.Push( "A" ); stack2.Push( "B" ); stack2.Push( "C" ); Console .WriteLine(stack2.Pop()); Console .WriteLine(stack2.Pop()); Console .WriteLine(stack2.Pop());
6. Life without Generics public class ExampleStack { private object [] contents = new object [99]; private int ptr ; public void Push( object o) { contents[++ptr] = o; } public object Pop() { return contents[ptr--]; } } What can go wrong ? ExampleStack stack2 = new ExampleStack (); stack2.Push( "A" ); stack2.Push( null ); stack2.Push( 12.7 ); Console .WriteLine(stack2.Pop()); Console .WriteLine(stack2.Pop()); Console .WriteLine(stack2.Pop());
7. Life with Generics public class ExampleStack <T> { private T[] contents = new T[99]; private int ptr; public void Push(T o) { contents[++ptr] = o; } public T Pop() { return contents[ptr--]; } } What can go wrong ? ExampleStack < int > stack1 = new ExampleStack < int >(); stack1.Push(32); stack1.Push(99); stack1.Push(101); // Wont compile // stack1.Push("string "); // stack1.Push('a'); Console .WriteLine(stack1.Pop()); Console .WriteLine(stack1.Pop()); Console .WriteLine(stack1.Pop());
8.
9. The 'Where' Clause public class ExampleStack <T> where T: IComparable { private T[] contents = new T[99]; private int ptr; public void Push(T o) { contents[++ptr] = o; } public T Pop() { return contents[ptr--]; } } Similar to SQL 'where' Enforces compile time checks on the generic May be Interfaces May enforce constructors E.G. new().new(int)
10. Multiple Generics public class ExampleStack <Tinterface, Tclass> where Tclass : Tinterface where Tinterface : ICloneable { private Tclass[] contents = new Tclass[99]; private int ptr; public void Push(Tclass o) { contents[++ptr] = o; } public Tinterface Pop() { return contents[ptr--]; } } Any number of Generic classes can be added ExampleStack < ICloneable , string > stack1 = new ExampleStack < ICloneable , string >(); stack1.Push( "Some String" ); ICloneable clone = stack1.Pop();
11. Generics are not just for classes! public interface Interface <T> { bool DoWork(T workItem); } public interface InterfaceString : Interface < string > { // now has method // bool DoWork(string workItem); } public class Implemetation : InterfaceString { public bool DoWork( string workItem) { // Do work return false ; } } Generics are not just for classes Interfaces Methods NOT Properties and Fields directly
12. Generics are not just for classes! public class Example { public T GenericMethod<T>(T obj1 , T obj2) where T: IComparable { if (obj1.CompareTo(obj2) > 0) return obj1; else return obj2; } } Generics are not just for classes Interfaces Methods NOT Properties and Fields directly