Everything You Never Wanted To Know About Net Generics

45
Martin L. Shoemaker Martin L. Shoemaker [email protected] [email protected] The Power of Ink is in Your Hands The Power of Ink is in Your Hands Copyright © 2007 by Martin L. Shoemaker Everything You Never Wanted to Everything You Never Wanted to Know About .NET Generics Know About .NET Generics (But Were Afraid Someone Would (But Were Afraid Someone Would Ask) Ask)

Transcript of Everything You Never Wanted To Know About Net Generics

Martin L. ShoemakerMartin L. [email protected]@InkonSoftware.com

The Power of Ink is in Your HandsThe Power of Ink is in Your Hands

Copyright © 2007 by Martin L. Shoemaker

Everything You Never Wanted to Everything You Never Wanted to Know About .NET GenericsKnow About .NET Generics

(But Were Afraid Someone Would (But Were Afraid Someone Would Ask)Ask)

• Software Developer since 1985.Software Developer since 1985.• Windows developer since 1989.Windows developer since 1989.• UML designer and trainer since 1997.UML designer and trainer since 1997.

• Founder of Inkon Software (Founder of Inkon Software (http://www.InkonSoftware.comhttp://www.InkonSoftware.com):):• Tablet PC and .NET software consulting.Tablet PC and .NET software consulting.• Inkon Logbook: An extensible platform for design, Inkon Logbook: An extensible platform for design,

data gathering, and note-taking applications using data gathering, and note-taking applications using pen and voice.pen and voice.

• Tablet UML, a UML tool for the Tablet PC (Tablet UML, a UML tool for the Tablet PC (http://www.TabletUML.comhttp://www.TabletUML.com).).

• Trainer & Creator of UML BootCamp, Tablet PC Trainer & Creator of UML BootCamp, Tablet PC BootCamp, and other courses for the Richard Hale Shaw BootCamp, and other courses for the Richard Hale Shaw Group (Group (http://www.RichardHaleShawGroup.comhttp://www.RichardHaleShawGroup.com).).

• Author of Author of UML Applied: A .NET PerspectiveUML Applied: A .NET Perspective from Apress from Apress and and Requirements Patterns and AntipatternsRequirements Patterns and Antipatterns, coming , coming soon from Addison-Wesley.soon from Addison-Wesley.

• Contact: Contact: [email protected]@InkonSoftware.com

Copyright © 2007 by Martin L. Shoemaker

BIO: Martin L. ShoemakerBIO: Martin L. Shoemaker

Copyright © 2007 by Martin L. Shoemaker

AgendaAgenda

• Lots of Boxes, or Just Box?Lots of Boxes, or Just Box?• Three “Solutions”Three “Solutions”• GenericsGenerics• Generics vs. C++ TemplatesGenerics vs. C++ Templates• .NET Generics vs. Java Generics.NET Generics vs. Java Generics• Generic Delegates and EventsGeneric Delegates and Events• Constraining Generic ParametersConstraining Generic Parameters• The The BoringBoring Generics Everybody Talks About Generics Everybody Talks About• The The CoolCool Generics Nobody Ever Talks About Generics Nobody Ever Talks About• Generics and SerializationGenerics and Serialization

Lots of Boxes…?Lots of Boxes…?

• Different kinds of boxes…?Different kinds of boxes…?

Copyright © 2007 by Martin L. Shoemaker

……or Just Box?or Just Box?

• A place to put stuff.A place to put stuff.• A lid that opens and closes.A lid that opens and closes.• A latch that latches or A latch that latches or

unlatches.unlatches.

Who cares what’s in it? Who cares what’s in it? It’s a It’s a box!box!

Copyright © 2007 by Martin L. Shoemaker

Lots of Boxes, or Just Box?Lots of Boxes, or Just Box?

Copyright © 2007 by Martin L. Shoemaker

• But what if you mix up the boxes?But what if you mix up the boxes?

Four “Solutions”Four “Solutions”

• InheritanceInheritance• TypelessTypeless• InterfacesInterfaces• WrappersWrappers

Copyright © 2007 by Martin L. Shoemaker

Four “Solutions”: InheritanceFour “Solutions”: Inheritance

• Inherit contents from a base class:Inherit contents from a base class:class Contents;class Contents;

class Food : Contents {}class Food : Contents {}

class Tool : Contents {}class Tool : Contents {}

etc…etc…

• Contain the base class:Contain the base class:class Boxclass Box

{{ public Contents stuff; }public Contents stuff; }

Copyright © 2007 by Martin L. Shoemaker

Four “Solutions”: InheritanceFour “Solutions”: Inheritance

• Problems:Problems:• Horribly abuses inheritance.Horribly abuses inheritance.• Requires the designers of Food and Tool to Requires the designers of Food and Tool to

know that the classes will be put in Boxes.know that the classes will be put in Boxes.• In a single-inheritance environment (like .NET), In a single-inheritance environment (like .NET),

ties the designer’s hands.ties the designer’s hands.• Doesn’t solve the Ice Cream in the Tool Box Doesn’t solve the Ice Cream in the Tool Box

problem.problem.

Copyright © 2007 by Martin L. Shoemaker

Four “Solutions”: TypelessFour “Solutions”: Typeless

• Inherit contents from Inherit contents from thethe base class, object: base class, object:class Food {}class Food {}

class Tool {}class Tool {}

etc…etc…

• Contain Contain thethe base class: base class:class Boxclass Box

{{ public object stuff; }public object stuff; }

Copyright © 2007 by Martin L. Shoemaker

Four “Solutions”: TypelessFour “Solutions”: Typeless

Copyright © 2007 by Martin L. Shoemaker

Four “Solutions”: InterfacesFour “Solutions”: Interfaces

• Content classes implement an interface:Content classes implement an interface:interface IContents;interface IContents;

class Food : IContents {}class Food : IContents {}

class Tool : IContents {}class Tool : IContents {}

etc…etc…

• Contain the interface:Contain the interface:class Boxclass Box

{{ public IContents stuff; }public IContents stuff; }

Copyright © 2007 by Martin L. Shoemaker

Four “Solutions”: InterfacesFour “Solutions”: Interfaces

Copyright © 2007 by Martin L. Shoemaker

Four “Solutions”: WrappersFour “Solutions”: Wrappers

• Wrap the box class:Wrap the box class:class Boxclass Box

{{ public object stuff; }public object stuff; }

class ToolBox : Boxclass ToolBox : Box

{{

public void SetTool(Tool tool)public void SetTool(Tool tool)

{ stuff = tool; }{ stuff = tool; }

public Tool GetTool()public Tool GetTool()

{ return stuff as Tool; }{ return stuff as Tool; }

}}

Copyright © 2007 by Martin L. Shoemaker

Four “Solutions”: WrappersFour “Solutions”: Wrappers

Copyright © 2007 by Martin L. Shoemaker

GenericsGenerics

• Classes, methods, interfaces, delegates, and Classes, methods, interfaces, delegates, and events designed to work with one or more events designed to work with one or more “placeholder” types.“placeholder” types.

• Placeholders are filled in when you use the Placeholders are filled in when you use the generic.generic.

class Box<T> { public T stuff; }class Box<T> { public T stuff; }

……

Box<Tool> toolbox = new Box<Tool>();Box<Tool> toolbox = new Box<Tool>();

toolbox.Stuff = new Hammer(); //OK.toolbox.Stuff = new Hammer(); //OK.

toolbox.Stuff = new toolbox.Stuff = new IceCreamSandwich(); //Compiler error.IceCreamSandwich(); //Compiler error.

Copyright © 2007 by Martin L. Shoemaker

GenericsGenerics

• Don’t abuse inheritance Don’t abuse inheritance oror interfaces. interfaces.• Don’t require the designers of Food and Tool Don’t require the designers of Food and Tool

to know that the classes will be put in Boxes.to know that the classes will be put in Boxes.• Don’t tie the designer’s hands.Don’t tie the designer’s hands.• Solves the Ice Cream in the Tool Box problem: Solves the Ice Cream in the Tool Box problem:

the compiler type-checks.the compiler type-checks.• Not a kludge! It’s a language/environment Not a kludge! It’s a language/environment

construct.construct.• Easy! It’s a language/environment construct.Easy! It’s a language/environment construct.

Copyright © 2007 by Martin L. Shoemaker

GenericsGenerics

Examples:Examples:• Calendar(Of T)Calendar(Of T)• Lunch MenuLunch Menu• Work ScheduleWork Schedule

Copyright © 2007 by Martin L. Shoemaker

Generics vs. C++ TemplatesGenerics vs. C++ Templates

Generics are inspired by C++ templates, but… Generics are inspired by C++ templates, but… • Generics do not support non-type parameters Generics do not support non-type parameters

(i.e., integers).(i.e., integers).• Generics do not support specialization (i.e., Generics do not support specialization (i.e.,

custom implementations templates for custom implementations templates for specific types).specific types).

• Generics cannot use a parameter type as a Generics cannot use a parameter type as a base class.base class.

• Generics cannot have default types.Generics cannot have default types.

Copyright © 2007 by Martin L. Shoemaker

Generics vs. C++ TemplatesGenerics vs. C++ Templates

Generics are inspired by C++ templates, but Generics are inspired by C++ templates, but (continued)… (continued)…

• A generic type parameter cannot itself be a A generic type parameter cannot itself be a generic.generic.

• C++ allows code that might be invalid for C++ allows code that might be invalid for some types, and then checks on use. .NET some types, and then checks on use. .NET generics require all code to be valid for all generics require all code to be valid for all valid types. (See constraints, below.)valid types. (See constraints, below.)

Copyright © 2007 by Martin L. Shoemaker

.NET Generics vs. Java Generics.NET Generics vs. Java Generics

Did you see the word “Java” Did you see the word “Java” anywhereanywhere on my on my bio slide?bio slide?

• I have absolutely no knowledge of Java I have absolutely no knowledge of Java generics.generics.

• Java folks have told me there’s a lot of Java folks have told me there’s a lot of similarity.similarity.

• It It isis an important question. an important question.• Feedback from the floor?Feedback from the floor?

Copyright © 2007 by Martin L. Shoemaker

Generic Delegates and EventsGeneric Delegates and Events

• Generics aren’t just for classes and interfaces.Generics aren’t just for classes and interfaces.• Generic delegates can be filled by any Generic delegates can be filled by any

methods which match the signatures.methods which match the signatures.• Events can be defined for generic delegates.Events can be defined for generic delegates.• Example:Example:• CalendarChange(Of T)CalendarChange(Of T)

Copyright © 2007 by Martin L. Shoemaker

Constraining Generic ParametersConstraining Generic Parameters

• When you declare a generic, you can When you declare a generic, you can constrain the parameters to certain types.constrain the parameters to certain types.

• The generic code can then call methods, The generic code can then call methods, properties, etc., implied by the constraints.properties, etc., implied by the constraints.

• Constraints:Constraints:• as Structure. Type must be value type.as Structure. Type must be value type.• as Class. Type must be reference type.as Class. Type must be reference type.• as New. Type must have a default constructor.as New. Type must have a default constructor.• as Base. Type must inherit from Base. (May be as Base. Type must inherit from Base. (May be

another type parameter.)another type parameter.)• as IBase. Type must implement IBase.as IBase. Type must implement IBase.

Copyright © 2007 by Martin L. Shoemaker

Constraining Generic ParametersConstraining Generic Parameters

Examples…Examples…

Copyright © 2007 by Martin L. Shoemaker

The The BoringBoring Generics Everybody Generics Everybody Talks About…Talks About…

……i.e., collections.i.e., collections.• The basic collection interfaces.The basic collection interfaces.• The list collections.The list collections.• The keyed collections.The keyed collections.

Copyright © 2007 by Martin L. Shoemaker

The The BoringBoring Generics: The Basic Generics: The Basic Collection InterfacesCollection Interfaces

Not very useful by themselves, but the useful Not very useful by themselves, but the useful collections build on them.collections build on them.

• ICollection<T>. Basic collection behavior: ICollection<T>. Basic collection behavior: Count, IsReadOnly, Add, Clear, Contains, Count, IsReadOnly, Add, Clear, Contains, CopyTo, Remove.CopyTo, Remove.

• IEnumerable<T>. Means a collection may be IEnumerable<T>. Means a collection may be “walked” via GetEnumerator.“walked” via GetEnumerator.

• IEnumerator<T>. Walks a collection: Current; IEnumerator<T>. Walks a collection: Current; MoveNext; Reset .MoveNext; Reset .

Copyright © 2007 by Martin L. Shoemaker

The The BoringBoring Generics: The List Generics: The List CollectionsCollections

• IList. Basic list behavior: ICollection<T>; IList. Basic list behavior: ICollection<T>; IEnumerable<T>; Item; IndexOf ; Insert; IEnumerable<T>; Item; IndexOf ; Insert; RemoveAt.RemoveAt.

• List. Stock implementation of IList.List. Stock implementation of IList.• LinkedList. Doubly linked list. LinkedList. Doubly linked list. • Queue. A FIFO list. Queue. A FIFO list. • Stack. A LIFO list.Stack. A LIFO list.

Copyright © 2007 by Martin L. Shoemaker

The The BoringBoring Generics: The List Generics: The List CollectionsCollections

• SynchronizedCollection. Thread-safe SynchronizedCollection. Thread-safe implementation of IList.implementation of IList.

• SynchronizedReadOnlyCollection . Thread-SynchronizedReadOnlyCollection . Thread-safe implementation of Ilist, but throws an safe implementation of Ilist, but throws an exception at any attempt to change the list.exception at any attempt to change the list.• Um, hello? What about compile-time checking?Um, hello? What about compile-time checking?

Copyright © 2007 by Martin L. Shoemaker

The The BoringBoring Generics: The List Generics: The List CollectionsCollections

Example:Example:• Calendar(Of T)Calendar(Of T)

Copyright © 2007 by Martin L. Shoemaker

The The BoringBoring Generics: The Keyed Generics: The Keyed CollectionsCollections

• IDictionary. Defines key/value lookup IDictionary. Defines key/value lookup behavior: Item; Keys; Values; Add; behavior: Item; Keys; Values; Add; ContainsKey; Remove; TryGetValue .ContainsKey; Remove; TryGetValue .

• Dictionary. Stock implementation of Dictionary. Stock implementation of IDictionary.IDictionary.

• KeyedByTypeCollection. Implementation of KeyedByTypeCollection. Implementation of Idictionary, with types as keys.Idictionary, with types as keys.

Copyright © 2007 by Martin L. Shoemaker

The The BoringBoring Generics: The Keyed Generics: The Keyed CollectionsCollections

• SortedList. Small memory binary-tree SortedList. Small memory binary-tree implementation of IDictionary and IList.implementation of IDictionary and IList.

• SortedDictionary. Fast insertion binary-tree SortedDictionary. Fast insertion binary-tree implementation of IDictionary and IList.implementation of IDictionary and IList.

• SynchronizedKeyedCollection. Thread-safe SynchronizedKeyedCollection. Thread-safe implementation of IDictionary.implementation of IDictionary.

Copyright © 2007 by Martin L. Shoemaker

The The BoringBoring Generics: The Keyed Generics: The Keyed CollectionsCollections

Example:Example:• Calendar(Of T)Calendar(Of T)

Copyright © 2007 by Martin L. Shoemaker

The The CoolCool Generics Nobody Ever Generics Nobody Ever Talks AboutTalks About

• Comparison Interfaces, Classes, and Comparison Interfaces, Classes, and DelegatesDelegates

• Other DelegatesOther Delegates• MiscellaneousMiscellaneous

Copyright © 2007 by Martin L. Shoemaker

The The CoolCool Generics: Comparison Generics: Comparison Interfaces, Classes, and DelegatesInterfaces, Classes, and Delegates

• IComparable(Of T). Indicates a type can be IComparable(Of T). Indicates a type can be compared to a particular type (usually itself) compared to a particular type (usually itself) using CompareTo.using CompareTo.

• Comparison(Of T). Delegate for comparing two Comparison(Of T). Delegate for comparing two instances of a particular type using Compare.instances of a particular type using Compare.

• IComparer(Of T). Indicates a type that can IComparer(Of T). Indicates a type that can compare two instances of a particular type compare two instances of a particular type using Compare.using Compare.

• Comparer(Of T). A stock implementation of Comparer(Of T). A stock implementation of IComparer.IComparer.

Copyright © 2007 by Martin L. Shoemaker

The The CoolCool Generics: Comparison Generics: Comparison Interfaces, Classes, and DelegatesInterfaces, Classes, and Delegates

• IEquatable(Of T): Indicates a type can be IEquatable(Of T): Indicates a type can be tested for equality with a particular type tested for equality with a particular type (usually itself) using Equals.(usually itself) using Equals.

• IEqualityComparer(Of T): Indicates a type that IEqualityComparer(Of T): Indicates a type that can test two instances of a particular type for can test two instances of a particular type for equality using Equals.equality using Equals.

• EqualityComparer(Of T). A stock EqualityComparer(Of T). A stock implementation of IEqualityComparer.implementation of IEqualityComparer.

Copyright © 2007 by Martin L. Shoemaker

The The CoolCool Generics: Comparison Generics: Comparison Interfaces, Classes, and DelegatesInterfaces, Classes, and Delegates

Examples…Examples…

Copyright © 2007 by Martin L. Shoemaker

The The CoolCool Generics: Other Generics: Other DelegatesDelegates

• Action(Of T).Action(Of T).• Delegate for a method that operates on an Delegate for a method that operates on an

object of type T.object of type T.• List(Of T).ForEach and Array.ForEach take an List(Of T).ForEach and Array.ForEach take an

Action(Of T) delegate and automates walking Action(Of T) delegate and automates walking the list.the list.

• Example…Example…

Copyright © 2007 by Martin L. Shoemaker

The The CoolCool Generics: Other Generics: Other DelegatesDelegates

• Predicate(Of T).Predicate(Of T).• Delegate for a method that determines whether Delegate for a method that determines whether

an object of type T meets some criterion.an object of type T meets some criterion.• List(Of T) and Array:List(Of T) and Array:• Exists. Does any element meet the criterion?Exists. Does any element meet the criterion?• Find. Find an element that meets the criterion.Find. Find an element that meets the criterion.• FindAll. Get a list of all elements that meet the FindAll. Get a list of all elements that meet the

criterion.criterion.• FindIndex. Find the index of an element that FindIndex. Find the index of an element that

meets the criterion.meets the criterion.

Copyright © 2007 by Martin L. Shoemaker

The The CoolCool Generics: Other Generics: Other DelegatesDelegates

• Predicate(Of T).Predicate(Of T).• List(Of T) and Array:List(Of T) and Array:• FindLast. Find the last element that meets the FindLast. Find the last element that meets the

criterion.criterion.• FindLastIndex. Find the index of the last element FindLastIndex. Find the index of the last element

that meets the criterion.that meets the criterion.• RemoveAll. Removes all elements that meet the RemoveAll. Removes all elements that meet the

criterion.criterion.• TrueForAll. True if all elements meet the TrueForAll. True if all elements meet the

criterion.criterion.

• Examples…Examples…

Copyright © 2007 by Martin L. Shoemaker

The The CoolCool Generics: Other Generics: Other DelegatesDelegates

• Converter(Of TInput, TOutput).Converter(Of TInput, TOutput).• Converts objects of one type to another.Converts objects of one type to another.• Used by List(Of T).ConvertAll and Used by List(Of T).ConvertAll and

Array.ConvertAll.Array.ConvertAll.• Example…Example…

• EventHandler(Of TEventArgs).EventHandler(Of TEventArgs).• Delegate which takes a sender object and a Delegate which takes a sender object and a

subclass of EventArgs.subclass of EventArgs.• Allows declaration of “standard” events Allows declaration of “standard” events

without having to define new delegates.without having to define new delegates.• Example…Example…

Copyright © 2007 by Martin L. Shoemaker

The The CoolCool Generics: Miscellaneous Generics: Miscellaneous

• NullableNullable• ArraySegmentArraySegment

Copyright © 2007 by Martin L. Shoemaker

Generics and SerializationGenerics and Serialization

• The bad news: XML serialization doesn’t The bad news: XML serialization doesn’t support generics.support generics.

• The good news: Binary serialization does.The good news: Binary serialization does.

Copyright © 2007 by Martin L. Shoemaker

Copyright © 2007 by Martin L. Shoemaker

ConclusionConclusion

• Generics define classes, methods, interfaces, Generics define classes, methods, interfaces, delegates, and events independent of the delegates, and events independent of the types they operate on.types they operate on.

• Types can be constrained.Types can be constrained.• .NET Framework provides a number of useful .NET Framework provides a number of useful

generics for collections and more.generics for collections and more.

Copyright © 2007 by Martin L. Shoemaker

Questions...Questions...

[email protected]@InkonSoftware.com

Martin L. ShoemakerMartin L. [email protected]@InkonSoftware.com

The Power of Ink is in Your HandsThe Power of Ink is in Your Hands

Copyright © 2007 by Martin L. Shoemaker

Everything You Never Wanted to Everything You Never Wanted to Know About .NET GenericsKnow About .NET Generics

(But Were Afraid Someone Would (But Were Afraid Someone Would Ask)Ask)