9.12. Creating a Hashtable with Max and Min Value Boundaries

Problem

You need to use a Hashtable in your project that stores only numeric data between a set maximum and minimum value.

Solution

Create a class whose accessors and methods enforce these boundaries. This class, MaxMinValueHashtable, allows only integer values that fall between a maximum and minimum size to be stored:

using System; using System.Collections; [Serializable] public class MaxMinValueHashtable : Hashtable { public MaxMinValueHashtable( ) : base( ) { } public MaxMinValueHashtable(int minValue, int maxValue) : base( ) { this.minValue = minValue; this.maxValue = maxValue; } protected int minValue = int.MinValue; protected int maxValue = int.MaxValue; 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 (value is int) { if ((int)value >= minValue && (int)value <= maxValue) { base[key] = value; } else { throw (new ArgumentOutOfRangeException("value", value, "Value must be within the range " + minValue + " to " + maxValue)); } } else { base[key] = value; } } else { throw (new ArgumentOutOfRangeException("value", value, "This Hashtable is currently set to read-only.")); } } } // This method has been overridden to allow objects to be // stored in this Hashtable, as well as integers. // If you do not wish objects ...

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.