title: Need to Compare Two Generic Objects Using Greater Than or Less Than
body: <p><strong>Synopsis:</strong> I have a need to take two generic C# objects, and if they are numerical, compare them using either less than or greater than comparisons.</p>
  
  <p><strong>Problem</strong>: I can't figure out how to have my class implement IComparable as described in this post: <a href="https://stackoverflow.com/questions/2357410/having-to-implement-a-generic-less-than-and-greater-than-operation">Having to implement a generic less than and greater than operation</a>.  If that's not even the proper path to take, then I need to know that as well.</p>
  
  <p><strong>Background:</strong> I have implemented the RequiredIf ValidationAttribute found at <a href="http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2" rel="noreferrer">A more complex custom validator</a> but needed the > and &lt; options in addition to an equals comparison.</p>
  
  <p><strong>Code</strong> (taken from <a href="http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2" rel="noreferrer">A more complex custom validator</a>, one-third down the page):</p>
  
  <pre><code>private bool IsRequired(object actualPropertyValue)
  {
    switch (Comparison)
    {
      case Comparison.IsLessThan:
      case Comparison.IsLessThanOrEqualTo:
      case Comparison.IsGreaterThan:
      case Comparison.IsGreaterThanOrEqualTo:
        if (!Value.IsNumber())
        {
          throw new Exception("The selected comparison option is only applicable to numeric values");
        }
        break;
    }
  
    switch (Comparison)
    {
      case Comparison.IsNotEqualTo:
        return actualPropertyValue == null || !actualPropertyValue.Equals(Value);
      case Comparison.IsEqualTo:
        return actualPropertyValue != null &amp;&amp; actualPropertyValue.Equals(Value);
      case Comparison.IsGreaterThan:
        // THIS LINE FAILS BECAUSE actualPropertyValue DOESN'T IMPLEMENT IComparable 
        return actualPropertyValue != null &amp;&amp; (actualPropertyValue.CompareTo(Value) &gt; 0); 
      // The rest of the comparison cases go here...
      default:
        throw new Exception("Comparison value is not defined");
    }
  }
  </code></pre>
  
  <p><strong>Static Helper Extensions:</strong></p>
  
  <pre><code>public static bool IsNumber(this object value)
  {
    if (value is sbyte) return true;
    if (value is byte) return true;
    if (value is short) return true;
    if (value is ushort) return true;
    if (value is int) return true;
    if (value is uint) return true;
    if (value is long) return true;
    if (value is ulong) return true;
    if (value is float) return true;
    if (value is double) return true;
    if (value is decimal) return true;
    return false;
  }
  </code></pre>