O'Reilly logo

C# 3.0 Cookbook, 3rd Edition by Stephen Teilhet, Jay Hilyard

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 11. Data Structures and Algorithms

11.0. Introduction

In this chapter, you will look at certain data structures and algorithms that are not available for you in the FCL through Version 3.5. Examples are provided for algorithms such as hash-code creation and string balancing. The FCL does not support every data structure you might need, so this chapter provides solutions for priority, binary and n-ary trees, and a multimap, as well as many other things.

11.1. Creating a Hash Code for a Data Type

Problem

You have created a class or structure that will be used as a key in a Hashtable or Dictionary<T,U>. You need to overload the GetHashCode method in order to return a good distribution of hash values (the Discussion section defines a good distribution of hash values). You also need to choose the best hash-code algorithm to use in the GetHashCode method of your object.

Solution

The following procedures implement hash-code algorithms and can be used to override the GetHashCode method. Included in the discussion of each method are the pros and cons of using it, as well as why you would want to use one instead of another.

In addition, it is desirable, for performance reasons, to use the return value of the GetHashCode method to determine whether the data contained within two objects is equal. Calling GetHashCode to return a hash value of two objects and comparing their hash values can be faster than calling the default implementation of Equals on the Object type, which individually tests ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required