Book Image

.NET 4.0 Generics Beginner's Guide

By : Sudipta Mukherjee
Book Image

.NET 4.0 Generics Beginner's Guide

By: Sudipta Mukherjee

Overview of this book

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
Table of Contents (20 chapters)
.NET 4.0 Generics
Credits
Foreword
About the Author
Acknowledgement
About the Reviewers
www.PacktPub.com
Preface
2
Lists
4
LINQ to Objects
Migration Cheat Sheet

Preface

Thanks for picking up this book. This is an example-driven book. You will learn about several generic containers and generic algorithms available in the .NET Framework and a couple of other majorly accepted APIs such as Power Collections and C5 by building several applications and programs.

Towards the end, several benchmarkings have been carried out to identify the best container for the job at hand.

What this book covers

Chapter 1. Why Generics?, introduces .NET Generics. We will examine the need for the invention of Generics in the .NET Framework. If you start with a feel of "Why should I learn Generics?", you will end with a feeling of "Why didn't I till now?"

Chapter 2. Lists, introduces you to several kinds of lists that .NET Generics has to offer. There are simple lists and associative lists. You shall see how simple lists can deliver amazing results avoiding any typecasting woes and boosting performance at the same time.

Chapter 3. Dictionaries, explains the need for associative containers and introduces you to the associative containers that .NET has to offer. If you need to keep track of one or multiple dependent variables while one independent variable changes, you need a dictionary. For example, say you want to build a spell check or an autocomplete service, you need a dictionary. This chapter will walk you through this. Along the way, you will pick up some very important concepts.

Chapter 4. LINQ to Objects, explains LINQ to objects using extension methods. LINQ or Language Integrated Query is a syntax that allows us to query collections unanimously. In this chapter, we will learn about some standard LINQ Standard Query Operators (LSQO) and then use them in unison to orchestrate an elegant query for any custom need.

Chapter 5. Observable Collections, introduces observable collections. Observing events on collections has been inherently difficult. That's going to change forever, thanks to observable collections. You can now monitor your collections for any change; whether some elements are added to the collection, some of them are deleted, change locations, and so on. In this chapter, you will learn about these collections.

Chapter 6. Concurrent Collections, covers concurrent collections that appeared in .NET 4.0. Multi-threaded applications are ubiquitous and that's the new expectation of our generation. We are always busy and impatient, trying to get a lot of things done at once. So concurrency is here and it is here to stay for a long time. Historically, there was no inbuilt support for concurrency in generic collections. Programmers had to ensure concurrency through primitive thread locking. You can still do so, but you now have an option to use the concurrent version of generic collections that support concurrency natively. This greatly simplifies the code. In this chapter, you will learn how to use them to build some useful applications such as simulating a survey engine.

Chapter 7. Power Collections, introduces several generic algorithms in PowerCollections and some handy generic containers. This collection API came from Wintellect (www.wintellect.com) at the time when .NET Generics was not big and had some very useful collections. However, now .NET Generics has grown to support all those types and even more. So that makes most of the containers defined in PowerCollections outdated. However, there are a lot of good general purpose generic algorithms that you will need but which are missing from the .NET Generics API. That's the reason this chapter is included. In this chapter, you will see how these generic algorithms can be used with any generic container seamlessly.

Chapter 8. C5 Collections, introduces the C5 API. If you come from a Java background and are wondering where your hash and tree-based data structures, are this is the chapter to turn to. However, from the usage perspective, all the containers available in C5 can be augmented with generic containers available in the .NET Framework. You are free to use them. This API is also home to several great generic algorithms that make life a lot easier. In this chapter, you will walk through the different collections and algorithms that C5 offers.

Chapter 9. Patterns, Practices, and Performance, covers some best practices when dealing with Generics and introduces the benchmarking strategy. In this chapter, we will use benchmarking code to see how different generic containers perform and then declare a winner in that field. For example, benchmarking shows that if you need a set, then HashSet<T> in the .NET Framework is the fastest you can get.

Appendix A. Performance Cheat Sheet, is a cheat sheet with all the performance measures for all containers. Keeping this handy would be extremely useful when you want to decide which container to use for the job at hand.

Appendix B. Migration Cheat Sheet, will show you how to migrate code from STL/JCF/PowerCollections/.NET 1.0 to the latest .NET Framework-compliant code. Migration will never be easier. Using this cheat sheet, it will be a no brainer. This is great for seasoned C++, Java, or .NET developers who are looking for a quick reference to .NET Generics in the latest framework.

What you need for this book

You will need the following software to use this book:

  • Visual Studio 2010 (any version will do, I have used the Ultimate Trial version)

  • LINQPad

Instructions to download this software are given in the respective chapters where they are introduced.

Who this book is for

This book is for you, if you want to know what .NET Generics is all about and how it can help solve real-world problems. It is assumed that readers are familiar with C# program constructs such as variable declaration, looping, branching, and so on. No prior knowledge in .NET Generics or generic programming is required.

This book also offers handy migration tips from other generic APIs available in other languages, such as STL in C++ or JCF in Java. So if you are trying to migrate your code to the .NET platform from any of these, then this book will be helpful.

Last but not the least, this book ends with generic patterns, best practices, and performance analysis for several generic containers. So, if you are an architect or senior software engineer and have to define coding standards, this will be very handy as a showcase of proofs to your design decisions.

Conventions

In this book, you will find several headings appearing frequently.

To give clear instructions of how to complete a procedure or task, we use:

Time for action — heading

  1. 1. Action 1

  2. 2. Action 2

  3. 3. Action 3

Instructions often need some extra explanation so that they make sense, so they are followed with:

What just happened?

This heading explains the working of tasks or instructions that you have just completed.

You will also find some other learning aids in the book, including:

Pop quiz heading

These are short, multiple choice questions intended to help you test your own understanding.

Have a go hero — heading

These set practical challenges and give you ideas for experimenting with what you have learned.

You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "Suppose, I want to maintain a list of my students, then we can do that by using ArrayList to store a list of such Student objects."

A block of code is set as follows:

private T[] Sort<T>(T[] inputArray)
{
//Sort input array in-place
//and return the sorted array
return inputArray;
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

Enumerable.Range(1, 100).Reverse().ToList()
.ForEach(n => nums.AddLast(n));

Any command-line input or output is written as follows:

Argument 1: cannot convert from 'int[]' to 'float[]'

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Then go to the File menu to create a console project."

Note

Warnings or important notes appear in a box like this.

Note

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title through the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books maybe a mistake in the text or the code we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website, or added to any list of existing errata, under the Errata section of that title.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.