10.8. Creating a Set Object

Problem

You need an object that contains a group of unordered objects. This object containing a set of data must be able to be compared to other objects containing sets of data, as well as have the following actions performed on them:

  • Union of the items contained by the two objects containing sets of data.

  • Intersection of the items contained by the two objects containing sets of data.

  • Difference of the items contained by the two objects containing sets of data.

Solution

Create a Set object, shown here:

using System; using System.Collections; using System.Text; public class Set : IEnumerable { private ArrayList internalSet = new ArrayList( ); public int Count { get {return (internalSet.Count);} } public object this[int index] { get { return (internalSet[index]); } set { if (internalSet.Contains(value)) { throw (new ArgumentException( "Duplicate object cannot be added to this set.")); } else { internalSet[index] = value; } } } public void Add(object obj) { if (internalSet.Contains(obj)) { throw (new ArgumentException( "Duplicate object cannot be added to this set.")); } else { internalSet.Add(obj); } } public void Remove(object obj) { if (internalSet.Contains(obj)) { throw (new ArgumentException("Object cannot be removed from " + "this set because it does not exist in this set.")); } else { internalSet.Remove(obj); } } public void RemoveAt(int index) { internalSet.RemoveAt(index); } public bool Contains(object obj) { return (internalSet.Contains(obj)); ...

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.