FREE BOOK

Chapter 2: Creating Versatile Types

Posted by SAMS Publishing Free Book | C# Language March 24, 2010
Tags: C#
This chapter is all about making your own objects as useful and versatile as possible. In many cases, this means implementing the standard interfaces that .NET provides or simply overriding base class methods.

Make Types Sortable

Scenario/Problem: Objects of your type will be sorted in a collection or otherwise compared to each other.

Solution: Because you often don't know how your type will be used, making the objects sortable is highly recommended whenever possible.

In the Vector3d class example, in order to make the objects comparable, we'll add an _id field and implement the IComparable<Vertex3d> interface.
The _id field will be what determines the order (it doesn't make much sense to sort on coordinates, generally).

The sorting function is simple. It takes an object of Vertex3d and returns one of three values:

< 0 this is less than other
0 this is same as other
> 0 this is greater than other

Within the CompareTo function, you can do anything you want to arrive at those values. In our case, we can do the comparison ourself or just call the same function on the _id field.

struct Vertex3d : IFormattable, IEquatable<Vertex3d>, IComparable<Vertex3d>
{
   private int _id;
   public int Id
   {
       get
       {
           return _id;
       }
       set
       {
           _id = value;
       }
   }
   public Vertex3d(double x, double y, double z)
   {
       _x = x;
       _y = y;
       _z = z;
       _id = 0;
   }
   ...
   public int CompareTo(Vertex3d other)
   {
       if (_id < other._id)
           return -1;
       if (_id == other._id)
           return 0;
       return 1;
       /* We could also just do this:

        * return _id.CompareTo(other._id);
        * */

   }

}

Total Pages : 12 56789

comments