Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Replacing the Hashtable with Its Generic Counterpart
|
271
Solution
Replace all occurrences of the System.Collections.Hashtable class with the faster
generic
System.Collections.Generic.Dictionary class.
Here is a simple example of using a
System.Collections.Hashtable object:
public static void UseNonGenericHashtable( )
{
// Create and populate a Hashtable.
Hashtable numbers = new Hashtable( );
numbers.Add(1, "one"); // Causes a boxing operation to occur for the key
numbers.Add(2, "two"); // Causes a boxing operation to occur for the key
// Display all key/value pairs in the Hashtable.
// Causes an unboxing operation to occur on each iteration for the key
foreach (DictionaryEntry de in numbers)
{
Console.WriteLine("Key: " + de.Key + "\tValue: " + de.Value);
}
numbers.Clear( );
}
Here is that same code using a System.Collections.Generic.Dictionary<T,U> object:
public static void UseGenericDictionary( )
{
// Create and populate a Dictionary.
Dictionary<int, string> numbers = new Dictionary<int, string>( );
numbers.Add(1, "one");
numbers.Add(2, "two");
// Display all key/value pairs in the Dictionary.
foreach (KeyValuePair<int, string> kvp in numbers)
{
Console.WriteLine("Key: " + kvp.Key + "\tValue: " + kvp.Value);
}
numbers.Clear( );
}
Discussion
For simple implementations of the Hashtable ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata