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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.