SlideShare a Scribd company logo
Everything You Never Wanted to Know About .NET Generics (But Were Afraid Someone Would Ask) Copyright © 2007 by Martin L. Shoemaker
Software Developer since 1985. Windows developer since 1989. UML designer and trainer since 1997. Founder of Inkon Software ( http://www.InkonSoftware.com ): Tablet PC and .NET software consulting. Inkon Logbook: An extensible platform for design, data gathering, and note-taking applications using pen and voice. Tablet UML, a UML tool for the Tablet PC ( http://www.TabletUML.com ). Trainer & Creator of UML BootCamp, Tablet PC BootCamp, and other courses for the Richard Hale Shaw Group ( http://www.RichardHaleShawGroup.com ). Author of  UML Applied: A .NET Perspective  from Apress and  Requirements Patterns and Antipatterns , coming soon from Addison-Wesley. Contact:  [email_address] BIO: Martin L. Shoemaker Copyright © 2007 by Martin L. Shoemaker
Agenda Lots of Boxes, or Just Box? Three “Solutions” Generics Generics vs. C++ Templates .NET Generics vs. Java Generics Generic Delegates and Events Constraining Generic Parameters The  Boring  Generics Everybody Talks About The  Cool  Generics Nobody Ever Talks About Generics and Serialization Copyright © 2007 by Martin L. Shoemaker
Lots of Boxes…? Different kinds of boxes…? Copyright © 2007 by Martin L. Shoemaker
… or Just Box? A place to put stuff. A lid that opens and closes. A latch that latches or unlatches. Who cares what’s in it?  It’s a box! Copyright © 2007 by Martin L. Shoemaker
Lots of Boxes, or Just Box? But what if you mix up the boxes? Copyright © 2007 by Martin L. Shoemaker
Four “Solutions” Inheritance Typeless Interfaces Wrappers Copyright © 2007 by Martin L. Shoemaker
Four “Solutions”: Inheritance Inherit contents from a base class: class Contents; class Food : Contents {} class Tool : Contents {} etc… Contain the base class: class Box { public Contents stuff; } Copyright © 2007 by Martin L. Shoemaker
Four “Solutions”: Inheritance Problems: Horribly abuses inheritance. Requires the designers of Food and Tool to know that the classes will be put in Boxes. In a single-inheritance environment (like .NET), ties the designer’s hands. Doesn’t solve the Ice Cream in the Tool Box problem. Copyright © 2007 by Martin L. Shoemaker
Four “Solutions”: Typeless Inherit contents from  the  base class, object: class Food {} class Tool {} etc… Contain  the  base class: class Box { public object stuff; } Copyright © 2007 by Martin L. Shoemaker
Four “Solutions”: Typeless Copyright © 2007 by Martin L. Shoemaker
Four “Solutions”: Interfaces Content classes implement an interface: interface IContents; class Food : IContents {} class Tool : IContents {} etc… Contain the interface: class Box { public IContents stuff; } Copyright © 2007 by Martin L. Shoemaker
Four “Solutions”: Interfaces Copyright © 2007 by Martin L. Shoemaker
Four “Solutions”: Wrappers Wrap the box class: class Box { public object stuff; } class ToolBox : Box { public void SetTool(Tool tool) { stuff = tool; } public Tool GetTool() { return stuff as Tool; } } Copyright © 2007 by Martin L. Shoemaker
Four “Solutions”: Wrappers Copyright © 2007 by Martin L. Shoemaker
Generics Classes, methods, interfaces, delegates, and events designed to work with one or more “placeholder” types. Placeholders are filled in when you use the generic. class Box<T> { public T stuff; } … Box<Tool> toolbox = new Box<Tool>(); toolbox.Stuff = new Hammer(); //OK. toolbox.Stuff = new IceCreamSandwich(); //Compiler error. Copyright © 2007 by Martin L. Shoemaker
Generics Don’t abuse inheritance  or  interfaces. Don’t require the designers of Food and Tool to know that the classes will be put in Boxes. Don’t tie the designer’s hands. Solves the Ice Cream in the Tool Box problem: the compiler type-checks. Not a kludge! It’s a language/environment construct. Easy! It’s a language/environment construct. Copyright © 2007 by Martin L. Shoemaker
Generics Examples: Calendar(Of T) Lunch Menu Work Schedule Copyright © 2007 by Martin L. Shoemaker
Generics vs. C++ Templates Generics are inspired by C++ templates, but…  Generics do not support non-type parameters (i.e., integers). Generics do not support specialization (i.e., custom implementations templates for specific types). Generics cannot use a parameter type as a base class. Generics cannot have default types. Copyright © 2007 by Martin L. Shoemaker
Generics vs. C++ Templates Generics are inspired by C++ templates, but (continued)…  A generic type parameter cannot itself be a generic. C++ allows code that might be invalid for some types, and then checks on use. .NET generics require all code to be valid for all valid types. (See constraints, below.) Copyright © 2007 by Martin L. Shoemaker
.NET Generics vs. Java Generics Did you see the word “Java”  anywhere  on my bio slide? I have absolutely no knowledge of Java generics. Java folks have told me there’s a lot of similarity. It  is  an important question. Feedback from the floor? Copyright © 2007 by Martin L. Shoemaker
Generic Delegates and Events Generics aren’t just for classes and interfaces. Generic delegates can be filled by any methods which match the signatures. Events can be defined for generic delegates. Example: CalendarChange(Of T) Copyright © 2007 by Martin L. Shoemaker
Constraining Generic Parameters When you declare a generic, you can constrain the parameters to certain types. The generic code can then call methods, properties, etc., implied by the constraints. Constraints: as Structure. Type must be value type. as Class. Type must be reference type. as New. Type must have a default constructor. as Base. Type must inherit from Base. (May be another type parameter.) as IBase. Type must implement IBase. Copyright © 2007 by Martin L. Shoemaker
Constraining Generic Parameters Examples… Copyright © 2007 by Martin L. Shoemaker
The  Boring  Generics Everybody Talks About… … i.e., collections. The basic collection interfaces. The list collections. The keyed collections. Copyright © 2007 by Martin L. Shoemaker
The  Boring  Generics: The Basic Collection Interfaces Not very useful by themselves, but the useful collections build on them. ICollection<T>. Basic collection behavior: Count, IsReadOnly, Add, Clear, Contains, CopyTo, Remove. IEnumerable<T>.  Means a collection may be “walked” via GetEnumerator. IEnumerator<T>.  Walks a collection:  Current; MoveNext; Reset . Copyright © 2007 by Martin L. Shoemaker
The  Boring  Generics: The List Collections IList. Basic list behavior: ICollection<T>; IEnumerable<T>; Item; IndexOf ; Insert; RemoveAt. List. Stock implementation of IList. LinkedList. Doubly linked list.  Queue. A FIFO list.  Stack. A LIFO list. Copyright © 2007 by Martin L. Shoemaker
The  Boring  Generics: The List Collections SynchronizedCollection. Thread-safe implementation of IList. SynchronizedReadOnlyCollection . Thread-safe implementation of Ilist, but throws an exception at any attempt to change the list. Um, hello? What about compile-time checking? Copyright © 2007 by Martin L. Shoemaker
The  Boring  Generics: The List Collections Example: Calendar(Of T) Copyright © 2007 by Martin L. Shoemaker
The  Boring  Generics: The Keyed Collections IDictionary. Defines key/value lookup behavior: Item; Keys; Values; Add; ContainsKey; Remove; TryGetValue . Dictionary. Stock implementation of IDictionary. KeyedByTypeCollection. Implementation of Idictionary, with types as keys. Copyright © 2007 by Martin L. Shoemaker
The  Boring  Generics: The Keyed Collections SortedList. Small memory binary-tree implementation of IDictionary and IList. SortedDictionary. Fast insertion binary-tree implementation of IDictionary and IList. SynchronizedKeyedCollection. Thread-safe implementation of IDictionary. Copyright © 2007 by Martin L. Shoemaker
The  Boring  Generics: The Keyed Collections Example: Calendar(Of T) Copyright © 2007 by Martin L. Shoemaker
The  Cool  Generics Nobody Ever Talks About Comparison Interfaces, Classes, and Delegates Other Delegates Miscellaneous Copyright © 2007 by Martin L. Shoemaker
The  Cool  Generics: Comparison Interfaces, Classes, and Delegates IComparable(Of T). Indicates a type can be compared to a particular type (usually itself) using CompareTo. Comparison(Of T). Delegate for comparing two instances of a particular type using Compare. IComparer(Of T). Indicates a type that can compare two instances of a particular type using Compare. Comparer(Of T). A stock implementation of IComparer. Copyright © 2007 by Martin L. Shoemaker
The  Cool  Generics: Comparison Interfaces, Classes, and Delegates IEquatable(Of T): Indicates a type can be tested for equality with a particular type (usually itself) using Equals. IEqualityComparer(Of T): Indicates a type that can test two instances of a particular type for equality using Equals. EqualityComparer(Of T). A stock implementation of IEqualityComparer. Copyright © 2007 by Martin L. Shoemaker
The  Cool  Generics: Comparison Interfaces, Classes, and Delegates Examples… Copyright © 2007 by Martin L. Shoemaker
The  Cool  Generics: Other Delegates Action(Of T). Delegate for a method that operates on an object of type T. List(Of T).ForEach and Array.ForEach take an Action(Of T) delegate and automates walking the list. Example… Copyright © 2007 by Martin L. Shoemaker
The  Cool  Generics: Other Delegates Predicate(Of T). Delegate for a method that determines whether an object of type T meets some criterion. List(Of T) and Array: Exists. Does any element meet the criterion? Find. Find an element that meets the criterion. FindAll. Get a list of all elements that meet the criterion. FindIndex. Find the index of an element that meets the criterion. Copyright © 2007 by Martin L. Shoemaker
The  Cool  Generics: Other Delegates Predicate(Of T). List(Of T) and Array: FindLast. Find the last element that meets the criterion. FindLastIndex. Find the index of the last element that meets the criterion. RemoveAll. Removes all elements that meet the criterion. TrueForAll. True if all elements meet the criterion. Examples… Copyright © 2007 by Martin L. Shoemaker
The  Cool  Generics: Other Delegates Converter(Of TInput, TOutput). Converts objects of one type to another. Used by List(Of T).ConvertAll and Array.ConvertAll. Example… EventHandler(Of TEventArgs). Delegate which takes a sender object and a subclass of EventArgs. Allows declaration of “standard” events without having to define new delegates. Example… Copyright © 2007 by Martin L. Shoemaker
The  Cool  Generics: Miscellaneous Nullable ArraySegment Copyright © 2007 by Martin L. Shoemaker
Generics and Serialization The bad news: XML serialization doesn’t support generics. The good news: Binary serialization does. Copyright © 2007 by Martin L. Shoemaker
Conclusion Generics define classes, methods, interfaces, delegates, and events independent of the types they operate on. Types can be constrained. .NET Framework provides a number of useful generics for collections and more. Copyright © 2007 by Martin L. Shoemaker
Questions... [email_address] Copyright © 2007 by Martin L. Shoemaker
Everything You Never Wanted to Know About .NET Generics (But Were Afraid Someone Would Ask) Copyright © 2007 by Martin L. Shoemaker

More Related Content

PPTX
C# coding standards, good programming principles & refactoring
PPTX
The right way coding for ios app development
PDF
Using Xcore with Xtext
PDF
ознакомления с модулем Entity api
PDF
Fields, entities, lists, oh my!
PPT
Oops in PHP By Nyros Developer
PDF
2016-11-12 02 Николай Линкер. Чему Java может поучиться у Haskell и наоборот
C# coding standards, good programming principles & refactoring
The right way coding for ios app development
Using Xcore with Xtext
ознакомления с модулем Entity api
Fields, entities, lists, oh my!
Oops in PHP By Nyros Developer
2016-11-12 02 Николай Линкер. Чему Java может поучиться у Haskell и наоборот

Similar to Everything You Never Wanted To Know About Net Generics (20)

PPTX
More Little Wonders of C#/.NET
PDF
Review of c_sharp2_features_part_i
PDF
Introduction to c#
PDF
Introduction To Csharp
PPTX
PPTX
Generics In and Out
PPTX
ODP
(4) collections algorithms
PDF
(4) collections algorithms
PPT
Generics_RIO.ppt
PPTX
Generics in .NET, C++ and Java
PPT
Introduction to csharp
PPT
Introduction to csharp
PPT
Introduction to csharp
PPTX
C# Generics
PDF
Net 40 Generics Beginners Guide Sudipta Mukherjee
PDF
Generics Tutorial
PDF
117 A Outline 25
More Little Wonders of C#/.NET
Review of c_sharp2_features_part_i
Introduction to c#
Introduction To Csharp
Generics In and Out
(4) collections algorithms
(4) collections algorithms
Generics_RIO.ppt
Generics in .NET, C++ and Java
Introduction to csharp
Introduction to csharp
Introduction to csharp
C# Generics
Net 40 Generics Beginners Guide Sudipta Mukherjee
Generics Tutorial
117 A Outline 25
Ad

Everything You Never Wanted To Know About Net Generics

  • 1. Everything You Never Wanted to Know About .NET Generics (But Were Afraid Someone Would Ask) Copyright © 2007 by Martin L. Shoemaker
  • 2. Software Developer since 1985. Windows developer since 1989. UML designer and trainer since 1997. Founder of Inkon Software ( http://www.InkonSoftware.com ): Tablet PC and .NET software consulting. Inkon Logbook: An extensible platform for design, data gathering, and note-taking applications using pen and voice. Tablet UML, a UML tool for the Tablet PC ( http://www.TabletUML.com ). Trainer & Creator of UML BootCamp, Tablet PC BootCamp, and other courses for the Richard Hale Shaw Group ( http://www.RichardHaleShawGroup.com ). Author of UML Applied: A .NET Perspective from Apress and Requirements Patterns and Antipatterns , coming soon from Addison-Wesley. Contact: [email_address] BIO: Martin L. Shoemaker Copyright © 2007 by Martin L. Shoemaker
  • 3. Agenda Lots of Boxes, or Just Box? Three “Solutions” Generics Generics vs. C++ Templates .NET Generics vs. Java Generics Generic Delegates and Events Constraining Generic Parameters The Boring Generics Everybody Talks About The Cool Generics Nobody Ever Talks About Generics and Serialization Copyright © 2007 by Martin L. Shoemaker
  • 4. Lots of Boxes…? Different kinds of boxes…? Copyright © 2007 by Martin L. Shoemaker
  • 5. … or Just Box? A place to put stuff. A lid that opens and closes. A latch that latches or unlatches. Who cares what’s in it? It’s a box! Copyright © 2007 by Martin L. Shoemaker
  • 6. Lots of Boxes, or Just Box? But what if you mix up the boxes? Copyright © 2007 by Martin L. Shoemaker
  • 7. Four “Solutions” Inheritance Typeless Interfaces Wrappers Copyright © 2007 by Martin L. Shoemaker
  • 8. Four “Solutions”: Inheritance Inherit contents from a base class: class Contents; class Food : Contents {} class Tool : Contents {} etc… Contain the base class: class Box { public Contents stuff; } Copyright © 2007 by Martin L. Shoemaker
  • 9. Four “Solutions”: Inheritance Problems: Horribly abuses inheritance. Requires the designers of Food and Tool to know that the classes will be put in Boxes. In a single-inheritance environment (like .NET), ties the designer’s hands. Doesn’t solve the Ice Cream in the Tool Box problem. Copyright © 2007 by Martin L. Shoemaker
  • 10. Four “Solutions”: Typeless Inherit contents from the base class, object: class Food {} class Tool {} etc… Contain the base class: class Box { public object stuff; } Copyright © 2007 by Martin L. Shoemaker
  • 11. Four “Solutions”: Typeless Copyright © 2007 by Martin L. Shoemaker
  • 12. Four “Solutions”: Interfaces Content classes implement an interface: interface IContents; class Food : IContents {} class Tool : IContents {} etc… Contain the interface: class Box { public IContents stuff; } Copyright © 2007 by Martin L. Shoemaker
  • 13. Four “Solutions”: Interfaces Copyright © 2007 by Martin L. Shoemaker
  • 14. Four “Solutions”: Wrappers Wrap the box class: class Box { public object stuff; } class ToolBox : Box { public void SetTool(Tool tool) { stuff = tool; } public Tool GetTool() { return stuff as Tool; } } Copyright © 2007 by Martin L. Shoemaker
  • 15. Four “Solutions”: Wrappers Copyright © 2007 by Martin L. Shoemaker
  • 16. Generics Classes, methods, interfaces, delegates, and events designed to work with one or more “placeholder” types. Placeholders are filled in when you use the generic. class Box<T> { public T stuff; } … Box<Tool> toolbox = new Box<Tool>(); toolbox.Stuff = new Hammer(); //OK. toolbox.Stuff = new IceCreamSandwich(); //Compiler error. Copyright © 2007 by Martin L. Shoemaker
  • 17. Generics Don’t abuse inheritance or interfaces. Don’t require the designers of Food and Tool to know that the classes will be put in Boxes. Don’t tie the designer’s hands. Solves the Ice Cream in the Tool Box problem: the compiler type-checks. Not a kludge! It’s a language/environment construct. Easy! It’s a language/environment construct. Copyright © 2007 by Martin L. Shoemaker
  • 18. Generics Examples: Calendar(Of T) Lunch Menu Work Schedule Copyright © 2007 by Martin L. Shoemaker
  • 19. Generics vs. C++ Templates Generics are inspired by C++ templates, but… Generics do not support non-type parameters (i.e., integers). Generics do not support specialization (i.e., custom implementations templates for specific types). Generics cannot use a parameter type as a base class. Generics cannot have default types. Copyright © 2007 by Martin L. Shoemaker
  • 20. Generics vs. C++ Templates Generics are inspired by C++ templates, but (continued)… A generic type parameter cannot itself be a generic. C++ allows code that might be invalid for some types, and then checks on use. .NET generics require all code to be valid for all valid types. (See constraints, below.) Copyright © 2007 by Martin L. Shoemaker
  • 21. .NET Generics vs. Java Generics Did you see the word “Java” anywhere on my bio slide? I have absolutely no knowledge of Java generics. Java folks have told me there’s a lot of similarity. It is an important question. Feedback from the floor? Copyright © 2007 by Martin L. Shoemaker
  • 22. Generic Delegates and Events Generics aren’t just for classes and interfaces. Generic delegates can be filled by any methods which match the signatures. Events can be defined for generic delegates. Example: CalendarChange(Of T) Copyright © 2007 by Martin L. Shoemaker
  • 23. Constraining Generic Parameters When you declare a generic, you can constrain the parameters to certain types. The generic code can then call methods, properties, etc., implied by the constraints. Constraints: as Structure. Type must be value type. as Class. Type must be reference type. as New. Type must have a default constructor. as Base. Type must inherit from Base. (May be another type parameter.) as IBase. Type must implement IBase. Copyright © 2007 by Martin L. Shoemaker
  • 24. Constraining Generic Parameters Examples… Copyright © 2007 by Martin L. Shoemaker
  • 25. The Boring Generics Everybody Talks About… … i.e., collections. The basic collection interfaces. The list collections. The keyed collections. Copyright © 2007 by Martin L. Shoemaker
  • 26. The Boring Generics: The Basic Collection Interfaces Not very useful by themselves, but the useful collections build on them. ICollection<T>. Basic collection behavior: Count, IsReadOnly, Add, Clear, Contains, CopyTo, Remove. IEnumerable<T>. Means a collection may be “walked” via GetEnumerator. IEnumerator<T>. Walks a collection: Current; MoveNext; Reset . Copyright © 2007 by Martin L. Shoemaker
  • 27. The Boring Generics: The List Collections IList. Basic list behavior: ICollection<T>; IEnumerable<T>; Item; IndexOf ; Insert; RemoveAt. List. Stock implementation of IList. LinkedList. Doubly linked list. Queue. A FIFO list. Stack. A LIFO list. Copyright © 2007 by Martin L. Shoemaker
  • 28. The Boring Generics: The List Collections SynchronizedCollection. Thread-safe implementation of IList. SynchronizedReadOnlyCollection . Thread-safe implementation of Ilist, but throws an exception at any attempt to change the list. Um, hello? What about compile-time checking? Copyright © 2007 by Martin L. Shoemaker
  • 29. The Boring Generics: The List Collections Example: Calendar(Of T) Copyright © 2007 by Martin L. Shoemaker
  • 30. The Boring Generics: The Keyed Collections IDictionary. Defines key/value lookup behavior: Item; Keys; Values; Add; ContainsKey; Remove; TryGetValue . Dictionary. Stock implementation of IDictionary. KeyedByTypeCollection. Implementation of Idictionary, with types as keys. Copyright © 2007 by Martin L. Shoemaker
  • 31. The Boring Generics: The Keyed Collections SortedList. Small memory binary-tree implementation of IDictionary and IList. SortedDictionary. Fast insertion binary-tree implementation of IDictionary and IList. SynchronizedKeyedCollection. Thread-safe implementation of IDictionary. Copyright © 2007 by Martin L. Shoemaker
  • 32. The Boring Generics: The Keyed Collections Example: Calendar(Of T) Copyright © 2007 by Martin L. Shoemaker
  • 33. The Cool Generics Nobody Ever Talks About Comparison Interfaces, Classes, and Delegates Other Delegates Miscellaneous Copyright © 2007 by Martin L. Shoemaker
  • 34. The Cool Generics: Comparison Interfaces, Classes, and Delegates IComparable(Of T). Indicates a type can be compared to a particular type (usually itself) using CompareTo. Comparison(Of T). Delegate for comparing two instances of a particular type using Compare. IComparer(Of T). Indicates a type that can compare two instances of a particular type using Compare. Comparer(Of T). A stock implementation of IComparer. Copyright © 2007 by Martin L. Shoemaker
  • 35. The Cool Generics: Comparison Interfaces, Classes, and Delegates IEquatable(Of T): Indicates a type can be tested for equality with a particular type (usually itself) using Equals. IEqualityComparer(Of T): Indicates a type that can test two instances of a particular type for equality using Equals. EqualityComparer(Of T). A stock implementation of IEqualityComparer. Copyright © 2007 by Martin L. Shoemaker
  • 36. The Cool Generics: Comparison Interfaces, Classes, and Delegates Examples… Copyright © 2007 by Martin L. Shoemaker
  • 37. The Cool Generics: Other Delegates Action(Of T). Delegate for a method that operates on an object of type T. List(Of T).ForEach and Array.ForEach take an Action(Of T) delegate and automates walking the list. Example… Copyright © 2007 by Martin L. Shoemaker
  • 38. The Cool Generics: Other Delegates Predicate(Of T). Delegate for a method that determines whether an object of type T meets some criterion. List(Of T) and Array: Exists. Does any element meet the criterion? Find. Find an element that meets the criterion. FindAll. Get a list of all elements that meet the criterion. FindIndex. Find the index of an element that meets the criterion. Copyright © 2007 by Martin L. Shoemaker
  • 39. The Cool Generics: Other Delegates Predicate(Of T). List(Of T) and Array: FindLast. Find the last element that meets the criterion. FindLastIndex. Find the index of the last element that meets the criterion. RemoveAll. Removes all elements that meet the criterion. TrueForAll. True if all elements meet the criterion. Examples… Copyright © 2007 by Martin L. Shoemaker
  • 40. The Cool Generics: Other Delegates Converter(Of TInput, TOutput). Converts objects of one type to another. Used by List(Of T).ConvertAll and Array.ConvertAll. Example… EventHandler(Of TEventArgs). Delegate which takes a sender object and a subclass of EventArgs. Allows declaration of “standard” events without having to define new delegates. Example… Copyright © 2007 by Martin L. Shoemaker
  • 41. The Cool Generics: Miscellaneous Nullable ArraySegment Copyright © 2007 by Martin L. Shoemaker
  • 42. Generics and Serialization The bad news: XML serialization doesn’t support generics. The good news: Binary serialization does. Copyright © 2007 by Martin L. Shoemaker
  • 43. Conclusion Generics define classes, methods, interfaces, delegates, and events independent of the types they operate on. Types can be constrained. .NET Framework provides a number of useful generics for collections and more. Copyright © 2007 by Martin L. Shoemaker
  • 44. Questions... [email_address] Copyright © 2007 by Martin L. Shoemaker
  • 45. Everything You Never Wanted to Know About .NET Generics (But Were Afraid Someone Would Ask) Copyright © 2007 by Martin L. Shoemaker