O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

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

9.11. Creating a Hashtable with Max and Min Size Boundaries

Problem

You need to use a Hashtable in your project that allows you to set the maximum and/or minimum number of elements that it can hold.

Solution

Use the MaxMinSizeHashtable class defined here. This class allows a definition of a maximum and a minimum size beyond which this MaxMinSizeHashtable cannot grow or shrink:

using System; using System.Collections; [Serializable] public class MaxMinSizeHashtable : Hashtable { public MaxMinSizeHashtable( ) : base(10) { } public MaxMinSizeHashtable(int minSize, int maxSize) : base(maxSize) { if (minSize >= 0 && maxSize > 0) { this.minSize = minSize; this.maxSize = maxSize; } } protected int minSize = 0; protected int maxSize = 10; // Initial size for a regular Hashtable protected bool readOnly = false; public bool ReadOnly { get {return (readOnly);} set {readOnly = value;} } public override bool IsReadOnly { get {return readOnly;} } public override object this[object key] { get { return (base[key]); } set { if (!readOnly) { if (key is long) { if (long.Parse(key.ToString( )) < maxSize && long.Parse(key.ToString( )) > minSize) { base[key] = value; } else { throw (new ArgumentOutOfRangeException("key", key, "The key is outside the minimum/maximum" + " boundaries.")); } } else { base[key] = value; } } else { throw (new ArgumentOutOfRangeException("value", value, "This Hashtable is currently set to read-only.")); } } } public override void Add(object key, object value) { if (!readOnly) ...

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