.NET 4.0 Generics Beginner’s Guide


.NET 4.0 Generics Beginner’s Guide
eBook: $29.99
Formats: PDF, PacktLib, ePub and Mobi formats
$25.49
save 15%!
Print + free eBook + free PacktLib access to the book: $79.98    Print cover: $49.99
$49.99
save 37%!
Free Shipping!
UK, US, Europe and selected countries in Asia.
Also available on:
Overview
Table of Contents
Author
Reviews
Support
Sample Chapters
  • 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

 

Book Details

Language : English
Paperback : 396 pages [ 235mm x 191mm ]
Release Date : January 2012
ISBN : 1849690782
ISBN 13 : 9781849690782
Author(s) : Sudipta Mukherjee
Topics and Technologies : All Books, Application Development, Microsoft Development , Beginner's Guides, Microsoft, .NET

Table of Contents

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

                        Sudipta Mukherjee

                        Sudipta was born in Kolkata and migrated to Bangalore, IT capital of india to assume the position of a senior research engineer in a renowned research lab. He is an Electronics engineer by education and a computer engineer/scientist by profession and passion. He graduated in 2004 with a degree in Electronics and Communication Engineering. He has been working with .NET Generics since they first appeared in .NET Framework 2.0 He has keen interest in Data structure, Algorithms, Text processing, Natural Language Processing ,Programming Language, Tools Development and Game Development. His first book on data structure using C programming language has been recevied quite well. Parts of the book can be read on Google Books http://goo.gl/pttSh The book also got translated to Simplified Chinese available from Amazon.cn at http://goo.gl/lc536 Sudipta is an active blogger and open source enthusiast. He mainly blogs about programming and related concepts at sudipta.posterous.com Inspired by several string processing methods in other languages, he created an Open Source string processing framework for .NET available for free use from stringdefs.codeplex.com He lives in Bangalore with his wife. He can be reached via email to sudipto80@yahoo.com and via twitter @samthecoder

                        Code Downloads

                        Download the code and support files for this book.


                        Submit Errata

                        Please let us know if you have found any errors not listed on this list by completing our errata submission form. Our editors will check them and add them to this list. Thank you.


                        Errata

                        - 2 submitted: last submission 18 Mar 2014

                        Errata type: Code | Page number: 60

                        MultiSet<char> firstPhrase = new MultiSet<char>("theeyes".ToCharArray());
                                   MultiSet<char> secondPhrase = new MultiSet<char>("theysee".ToCharArray());
                                    bool isAnagram = firstPhrase.Value.SequenceEquals(secondPhrase.Value);<br>
                        The VS2010 describe the error: Error1'System.Collections.Generic.IEnumerable' does not contain a definition for 'SequenceEquals' and no extension method 'SequenceEquals' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found.
                        Include System.Linq in the program.

                         

                         

                         

                        Errata type: Code | Page number: 29


                        The code statement should be changed from:

                        public static bool IsAnagram<T>(IEnumerable<T> first,
                        IEnumerable<T> second)

                        {
                          SortedList<T, int> val = new SortedList<<T, int>();

                        to

                        public static bool IsAnagram<T>(IEnumerable<T> first,
                        IEnumerable<T> second)
                        {
                          SortedList<T, int> val = new SortedList<T, int>();

                        Sample chapters

                        You can view our sample chapters and prefaces of this title on PacktLib or download sample chapters in PDF format.

                        Frequently bought together

                        .NET 4.0 Generics Beginner’s Guide +    Entity Framework 4.1: Expert’s Cookbook =
                        50% Off
                        the second eBook
                        Price for both: $45.60

                        Buy both these recommended eBooks together and get 50% off the cheapest eBook.

                        What you will learn from this book

                        • How different kinds of generic listsare related
                        • How to implement your own generic list
                        • Query every kind of generic container alike with Linq Standard Query Operators
                        • Augment .NET collections with general purpose algorithms available in C5 and PowerCollection
                        • Build concurrent apps in breathing easy steps.
                        • Find those algorithms you have been missing in .NET framework in PowerCollection and C5 API.
                        • Learn how different generic collections/containers perform under benchmarking, and when to use one over another
                        • Port your STL code blocks to .NET Generics which can be very handy if you are a veteran C++ developer and looking for an alternative in .NET world.

                         

                        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!

                        The author has also created a website (http://www.consulttoday.com/genguide) for the book where you can find many useful tools, code snippets, and, applications, which are not the part of code-download section

                        Approach

                        This is a concise, practical guide that will help you learn Generics in .NET, with lots of real world and fun-to-build examples and clear explanations. It is packed with screenshots to aid your understanding of the process.

                        Who this book is for

                        This book is aimed at beginners in Generics. It assumes some working knowledge of C# , but it isn’t mandatory.

                        The following would get the most use out of the book:

                        1. Newbie C# developers struggling with Generics.
                        2. Experienced C++ and Java Programmers who are migrating to C# and looking for an alternative to other generic frameworks like STL and JCF would find this book handy. 
                        3. Managers who want to know what Generics is and how to put it to good use.
                        4. Architects will find the benchmarking extremely useful, because it’s the first of its kind across a framework of several collections.

                        Code Download and Errata
                        Packt Anytime, Anywhere
                        Register Books
                        Print Upgrades
                        eBook Downloads
                        Video Support
                        Contact Us
                        Awards Voting Nominations Previous Winners
                        Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
                        Resources
                        Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software