Monday, 5 November 2007

Chapter 4, Lesson 5 - Generic Collections.

problem with ArrayList: it doesn't know what type of object users might want to store, so it simply stores instances of Object. This introduces runtime errors (e.g. casting to int in a foreach loop).

solution: generics - a collection class that supports basic colln interfaces (ICollection, IEnumerable), which uses ArrayList to collect items, Add() and indexer so that they are strongly-typed to a type specified by user. MyList myIntList = new MyList();

  • ArrayList -> List<> - Add, indexer, foreach for iterating - type-safe based on generic type param.
  • Sort() - new overload with generic delegate - public delegate int Comparison ( T x,T y )

Generic Dictionary Class

  • Hashtable, ListDictionary, OrderedDictionary, NameValueCollection -> Dictionary<>
  • specift type of key and value.
  • can use indexer.
  • Does not use DictionaryEntry obj to hold key/value pair. Use KeyValuePair instead.

No comments: