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) ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.