0

Can I write something like this in C#

class A<TBase> : TBase {}

Here's what I'm trying to do roughly:

public class Comparable<T, TBase> : TBase, IComparable<T>
{
   public abstract int CompareTo(T other);

   public static bool CompareTo(T x, T y) {
     return x != null ? x.CompareTo(y) : (y != null ? 1 : 0);
   }

   public static bool operator<(T x, T y) {
     return CompareTo(x, y) < 0;
   }

   public static bool operator<=(T x, T y) {
     return CompareTo(x, y) <= 0;
   }

   public static bool operator>(T x, T y) {
     return CompareTo(x, y) > 0;
   }

   public static bool operator>=(T x, T y) {
     return CompareTo(x, y) >= 0;
   }

   public static bool operator==(T x, T y) {
     return CompareTo(x, y) == 0;
   }

   public static bool operator!=(T x, T y) {
     return CompareTo(x, y) != 0;
   }
}

Response to comments, here's some examples of the duplicated code I'm trying to avoid:

class Height {
  // This needs to be a class not an int because we want to forbid 
  // silly things like multiplying heights
  private int _heightInMillimeters;

  // Lots of comparison operators here:
  // ... 
}

class Weight {
  // This needs to be a class not an int because we want to forbid 
  // silly things like multiplying weights by heights etc
  private double _weightInKilograms;

  // Lots of comparison operators here:
  // ... 
}

class SomeOtherClassThatIdLikeToCompare {
  // More boilerplate comparison operators here
}
21
  • Have you looked at using an interface? Commented May 15, 2018 at 4:58
  • How do I avoid having to define all six comparison operators for every class which implements the interface? Commented May 15, 2018 at 5:01
  • If you can post a bit more of code, it would be clearer what you are trying to do Commented May 15, 2018 at 5:07
  • @LowFlyingPelican cheers and done. See the edited question. Commented May 15, 2018 at 5:19
  • @Clinton Smells like an XY problem. Can you describe what you are ultimately trying to do? You seem to want to reduce duplicate code. Can you show how the code will be duplicated if you didn't use a generic parameter as base class? Commented May 15, 2018 at 5:39

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.