You are previewing .NET 4.0 Generics.
O'Reilly logo
.NET 4.0 Generics

Book Description

Enhance the type safety of your code and easily create applications using .Net Generics 4.0

  • Learn how to use Generics’ methods and generic collections to solve complicated problems.

  • Develop real-world applications using Generics

  • Know the importance of each generic collection and Generic class and use them as per your requirements

  • Benchmark the performance of all Generic collections

  • In Detail

    Generics were added as part of .NET Framework 2.0 in November 2005. Although similar to generics in Java, .NET generics do not apply type erasure but every object has unique representation at run-time. There is no performance hit from runtime casts and boxing conversions, which are normally expensive..NET offers type-safe versions of every classical data structure and some hybrid ones.

    This book will show you everything you need to start writing type-safe applications using generic data structures available in Generics API. You will also see how you can use several collections for each task you perform. This book is full of practical examples, interesting applications, and comparisons between Generics and more traditional approaches. Finally, each container is bench marked on the basis of performance for a given task, so you know which one to use and when.

    This book first covers the fundamental concepts such as type safety, Generic Methods, and Generic Containers. As the book progresses, you will learn how to join several generic containers to achieve your goals and query them efficiently using Linq. There are short exercises in every chapter to boost your knowledge.

    The book also teaches you some best practices, and several patterns that are commonly available in generic code.

    Some important generic algorithm definitions are present in Power Collection (an API created by Wintellect Inc.) that are missing from .NET framework. This book shows you how to use such algorithms seamlessly with other generic containers.

    The book also discusses C5 collections. Java Programmers will find themselves at home with this API. This is the closest to JCF. Some very interesting problems are solved using generic containers from .NET framework, C5, and PowerCollection Algorithms – a clone of Google Set and Gender Genie for example!

    Table of Contents

    1. .NET 4.0 Generics
    2. Credits
    3. Foreword
    4. About the Author
    5. Acknowledgement
    6. About the Reviewers
    7. www.PacktPub.com
      1. Support files, eBooks, discount offers and more
        1. Why Subscribe?
        2. Free Access for Packt account holders
    8. Preface
      1. What this book covers
      2. What you need for this book
      3. Who this book is for
      4. Conventions
      5. Time for action – heading
        1. What just happened?
        2. Pop quiz – heading
        3. Have a go hero – heading
      6. Reader feedback
      7. Customer support
        1. Downloading the example code
        2. Errata
        3. Piracy
        4. Questions
    9. 1. Why Generics?
      1. An analogy
        1. Reason 1: Generics can save you a lot of typing
        2. Reason 2: Generics can save you type safety woes, big time
          1. What's the problem with this approach?
        3. Reason 3: Generics leads to faster code
        4. Reason 4: Generics is now ubiquitous in the .NET ecosystem
      2. Setting up the environment
      3. Summary
    10. 2. Lists
      1. Why bother learning about generic lists?
      2. Types of generic lists
      3. Checking whether a sequence is a palindrome or not
      4. Time for action – creating the generic stack as the buffer
        1. What just happened?
      5. Time for action – completing the rest of the method
        1. What just happened?
      6. Designing a generic anagram finder
      7. Time for action – creating the method
        1. What just happened?
        2. Have a go hero – use this method to find anagrams from a dictionary
      8. Life is full of priorities, let's bring some order there
      9. Time for action – creating the data structure for the prioritized shopping list
        1. What just happened?
      10. Time for action – let's add some gadgets to the list and see them
        1. What just happened?
      11. Time for action – let's strike off the gadgets with top-most priority after we have bought them
        1. What just happened?
      12. Time for action – let's create an appointment list
        1. What just happened?
      13. Live sorting and statistics for online bidding
      14. Time for action – let's create a custom class for live sorting
        1. What just happened?
      15. Why did we have three LinkedList<T> as part of the data structure?
        1. Pop quiz
      16. An attempt to answer questions asked by your boss
      17. Time for action – associating products with live sorted bid amounts
        1. What just happened?
      18. Time for action – finding common values across different bidding amount lists
        1. What just happened?
        2. Have a go hero – finding common demographic statistics for the bidders
      19. You will win every scrabble game from now on
      20. Time for action – creating the method to find the character histogram of a word
      21. Time for action – checking whether a word can be formed
      22. Time for action – let's see whether it works
        1. Pop quiz
        2. Have a go hero – explain the code!
      23. Trying to fix an appointment with a doctor?
      24. Time for action – creating a set of dates of the doctors' availability
        1. What just happened?
      25. Time for action – finding out when both doctors shall be present
        1. What just happened?
        2. Pop quiz
      26. Revisiting the anagram problem
      27. Time for action – re-creating the anagram finder
        1. What just happened?
      28. Lists under the hood
      29. Summary
    11. 3. Dictionaries
      1. Types of generic associative structures
      2. Creating a tag cloud generator using dictionary
      3. Time for action – creating the word histogram
        1. What just happened?
        2. Have a go hero
        3. Pop quiz
      4. Creating a bubble wrap popper game
      5. Time for action – creating the game console
        1. What just happened?
      6. Look how easy it was!
      7. How did we decide we need a dictionary and not a list?
      8. Let's build a generic autocomplete service
      9. Time for action – creating a custom dictionary for autocomplete
        1. What just happened?
      10. Time for action – creating a class for autocomplete
        1. What just happened?
      11. The most common pitfall. Don't fall there!
      12. Let's play some piano
      13. Time for action – creating the keys of the piano
        1. What just happened?
      14. How are we recording the key strokes?
      15. Time for action – switching on recording and playing recorded keystrokes
        1. How it works?
      16. C# Dictionaries can help detect cancer. Let's see how!
      17. Time for action – creating the KNN API
        1. What just happened?
      18. Time for action – getting the patient records
      19. Time for action – creating the helper class to read a delimited file
        1. What just happened?
      20. Time for action – let's see how to use the predictor
        1. What just happened?
      21. Tuples are great for many occasions including games
      22. Time for action – putting it all together
        1. What just happened?
      23. Why have we used Tuples?
      24. How did we figure out whether the game is over or not?
        1. Have a go hero
      25. Summary
    12. 4. LINQ to Objects
      1. What makes LINQ?
        1. Extension methods
      2. Time for action – creating an Extension method
        1. What just happened?
      3. Time for action – consuming our new Extension method
        1. What just happened?
          1. Check out these guidelines for when not to use Extension methods
        2. Object initializers
        3. Collection initializers
        4. Implicitly typed local variables
        5. Anonymous types
        6. Lambda expressions
        7. Functors
        8. Predicates
        9. Actions
      4. Putting it all together, LINQ Standard Query Operators
      5. Time for action – getting the LINQPad
        1. Restriction operators
          1. Where()
      6. Time for action – finding all names with *am*
        1. What just happened?
      7. Time for action – finding all vowels
        1. What just happened?
      8. Time for action – finding all running processes matching a Regex
        1. What just happened?
      9. Time for action – playing with the indexed version of Where()
        1. What just happened?
      10. Time for action – learn how to go about creating a Where() clause
        1. What just happened?
        2. Pop quiz – doing the thing
        3. Projection operators
          1. Select()
      11. Time for action – let's say "Hello" to your buddies
        1. What just happened?
          1. Making use of the overloaded indexed version of Select()
      12. Time for action – radio "Lucky Caller" announcement
        1. What just happened?
        2. Have a go hero – can you tell me what's going on here?
          1. SelectMany()
      13. Time for action – flattening a dictionary
        1. What just happened?
        2. Partitioning operators
          1. Take()
      14. Time for action – leaving the first few elements
        1. What just happened?
          1. TakeWhile()
      15. Time for action – picking conditionally
        1. What just happened?
          1. Skip()
      16. Time for action – skipping save looping
        1. What just happened?
          1. SkipWhile()
        2. Ordering operators
          1. Reverse()
      17. Time for action – reversing word-by-word
        1. What just happened?
      18. Time for action – checking whether a given string is a palindrome or not
        1. What just happened?
          1. OrderBy()
            1. Sorting an array of strings alphabetically
      19. Time for action – sorting names alphabetically
        1. What just happened?
      20. Time for action – sorting 2D points by their co-ordinates
        1. What just happened?
        2. Have a go hero – sorting Student objects
          1. OrderByDescending()
          2. ThenBy()
      21. Time for action – sorting a list of fruits
          1. What's the difference between a sequence of OrderBy().OrderBy() and OrderBy().ThenBy()?
          2. ThenByDescending()
        1. Grouping operator
          1. GroupBy()
      22. Time for action – indexing an array of strings
        1. What just happened?
      23. Time for action – grouping by length
        1. What just happened?
        2. Set operators
          1. Intersect()
      24. Time for action – finding common names from two names' lists
        1. What just happened?
          1. Union()
      25. Time for action – finding all names from the list, removing duplicates
        1. What just happened?
          1. Concat()
      26. Time for action – pulling it all together including duplicates
          1. Except()
      27. Time for action – finding all names that appear mutually exclusively
        1. What just happened?
          1. Distinct()
      28. Time for action – removing duplicate song IDs from the list
        1. Conversion operators
          1. ToArray()
      29. Time for action – making sure it works!
        1. What just happened?
          1. ToList()
      30. Time for action – making a list out of IEnumerable<T>
        1. What just happened?
          1. ToDictionary()
      31. Time for action – tagging names
        1. What just happened?
          1. ToLookup()
      32. Time for action – one-to-many mapping
        1. What just happened?
        2. Element operators
          1. First()
      33. Time for action – finding the first element that satisfies a condition
        1. What just happened?
          1. How First() is different from Single()?
          2. FirstOrDefault()
      34. Time for action – getting acquainted with FirstOrDefault()
        1. What just happened?
          1. Last()
          2. LastOrDefault()
          3. SequenceEquals()
      35. Time for action – checking whether a sequence is palindromic
        1. What just happened?
          1. ElementAt()
      36. Time for action – understanding ElementAt()
        1. What just happened?
          1. ElementAtOrDefault()
          2. DefaultIfEmpty()
      37. Time for action – check out DefaultIfEmpty()
        1. What just happened?
        2. Generation operators
          1. Range()
      38. Time for action – generating arithmetic progression ranges
        1. What just happened?
      39. Time for action – running a filter on a range
        1. What just happened?
          1. Repeat()
      40. Time for action – let's go round and round with Repeat()
        1. What just happened?
        2. Quantifier operators
          1. Single()
      41. Time for action – checking whether there is only one item matching this pattern
        1. What just happened?
        2. Pop quiz – doing the thing
          1. SingleOrDefault()
      42. Time for action – set to default if there is more than one matching elements
          1. Any()
      43. Time for action – checking Any()
        1. What just happened?
          1. All()
      44. Time for action – how to check whether all items match a condition
        1. Merging operators
          1. Zip()
        2. What just happened?
      45. Summary
    13. 5. Observable Collections
      1. Active change/Statistical change
      2. Passive change/Non-statistical change
      3. Data sensitive change
      4. Time for action – creating a simple math question monitor
        1. What just happened?
      5. Time for action – creating the collections to hold questions
        1. What just happened?
      6. Time for action – attaching the event to monitor the collections
        1. What just happened?
      7. Time for action – dealing with the change as it happens
        1. What just happened?
      8. Time for action – dealing with the change as it happens
        1. What just happened?
      9. Time for action – putting it all together
        1. What just happened?
      10. Time for action – creating a Twitter browser
      11. Time for action – creating the interface
      12. Time for action – creating the TweetViewer user control design
      13. Time for action – gluing the TweetViewer control
      14. Time for action – putting everything together
        1. What just happened?
      15. Time for action – dealing with the change in the list of names in the first tab
        1. What just happened?
      16. Time for action – a few things to beware of at the form load
        1. What just happened?
      17. Time for action – things to do when names get added or deleted
        1. What just happened?
      18. Time for action – sharing the load and creating a task for each BackgroundWorker
        1. What just happened?
      19. Time for action – a sample run of the application
        1. Have a go hero – archive tweets
        2. Have a go hero – monitoring weather/stock
      20. Summary
    14. 6. Concurrent Collections
      1. Creating and running asynchronous tasks
        1. Pattern 1: Creating and starting a new asynchronous task
        2. Pattern 2: Creating a task and starting it off a little later
        3. Pattern 3: Waiting for all running tasks to complete
        4. Pattern 4: Waiting for any particular task
        5. Pattern 5: Starting a task with an initial parameter
      2. Simulating a survey (which is, of course, simultaneous by nature)
      3. Time for action – creating the blocks
        1. What just happened?
      4. Devising a data structure for finding the most in-demand item
      5. Time for action – creating the concurrent move-to-front list
        1. What just happened?
        2. Have a go hero – creating a virtual monitoring system
      6. Time for action – simulating a bank queue with multiple tellers
        1. What just happened?
      7. Time for action – making our bank queue simulator more useful
        1. What just happened?
      8. Be a smart consumer, don't wait till you have it all
      9. Exploring data structure mapping
      10. Summary
    15. 7. Power Collections
      1. Setting up the environment
      2. BinarySearch()
      3. Time for action – finding a name from a list of names
        1. What just happened?
      4. CartesianProduct()
      5. Time for action – generating names of all the 52 playing cards
        1. What just happened?
      6. RandomShuffle()
      7. Time for action – randomly shuffling the deck
        1. What just happened?
      8. NCopiesOf()
      9. Time for action – creating random numbers of any given length
        1. What just happened?
      10. Time for action – creating a custom random number generator
        1. What just happened?
      11. ForEach()
      12. Time for action – creating a few random numbers of given any length
        1. What just happened?
      13. Rotate() and RotateInPlace()
      14. Time for action – rotating a word
        1. What just happened?
      15. Time for action – creating a word guessing game
        1. What just happened?
        2. Have a go hero
      16. RandomSubset()
      17. Time for action – picking a set of random elements
        1. What just happened?
      18. Reverse()
      19. Time for action – reversing any collection
        1. What just happened?
      20. EqualCollections()
      21. Time for action – revisiting the palindrome problem
        1. What just happened?
      22. DisjointSets()
      23. Time for action – checking for common stuff
        1. What just happened?
      24. Time for action – finding anagrams the easiest way
        1. What just happened?
        2. Have a go hero
      25. Creating an efficient arbitrary floating point representation
      26. Time for action – creating a huge number API
        1. What just happened?
        2. Have a go hero
      27. Creating an API for customizable default values
      28. Time for action – creating a default value API
        1. What just happened?
      29. Mapping data structure
      30. Algorithm conversion strategy
      31. Summary
    16. 8. C5 Collections
      1. Setting up the environment
      2. Time for action – cloning Gender Genie!
        1. What just happened?
      3. Time for action – revisiting the anagram problem
        1. What just happened?
      4. Time for action – Google Sets idea prototype
        1. What just happened?
      5. Time for action – finding the most sought-after item
        1. What just happened?
      6. Sorting algorithms
        1. Pattern 1: Sorting an array of integers
        2. Pattern 2: Partially sorting an array—say, sort first five numbers of a long array
        3. Pattern 3: Sorting a list of string objects
      7. Summary
    17. 9. Patterns, Practices, and Performance
      1. Generic container patterns
        1. How these are organized
          1. Pattern 1: One-to-one mapping
            1. Pattern interface
            2. Some concrete implementations
            3. Example usages
            4. Some situations where this pattern can be used
          2. Pattern 2: One-to-many unique value mapping
            1. Pattern interface
            2. Some concrete implementations
            3. Example usages
            4. Some situations where this pattern can be used
          3. Pattern 3: One-to-many value mapping
            1. Pattern interface
            2. Some concrete implementations
            3. Example usages
            4. Some situations where this pattern can be used
          4. Pattern 4: Many-to-many mapping
            1. Pattern interface
            2. Some concrete implementations
            3. Example usages
            4. Some situations where this pattern can be used
      2. A special Tuple<> pattern
      3. Time for action – refactoring deeply nested if-else blocks
        1. What just happened?
      4. Best practices when using Generics
      5. Selecting a generic collection
      6. Best practices when creating custom generic collections
      7. Performance analysis
        1. Lists
        2. Dictionaries/associative containers
        3. Sets
      8. How would we do this investigation?
      9. Benchmarking experiment 1
      10. Benchmarking experiment 2
      11. Benchmarking experiment 3
      12. Benchmarking experiment 4
      13. Benchmarking experiment 5
      14. Benchmarking experiment 6
      15. Benchmarking experiment 7
      16. Benchmarking experiment 8
      17. Benchmarking experiment 9
      18. Summary
    18. A. Performance Cheat Sheet
      1. Parameters to consider
    19. B. Migration Cheat Sheet
    20. C. Pop Quiz Answers
      1. Chapter 2
        1. Lists
      2. Chapter 3
        1. Dictionaries
      3. Chapter 4
        1. LINQ to Objects