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

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