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

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

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