Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata