You need to compare two common objects using larger or smaller than

Summary: I need to take two common C # objects, and if they are numerical, compare them using either fewer or more comparisons.

Problem : I cannot figure out how to implement my IComparable class, as described in this post: The need to implement the overall size is smaller and larger than the operation . If this is not even the right way, I should know this as well.

Background: I implemented the RequiredIf ValidationAttribute found in the More sophisticated custom validator , but this requires> and <options in addition to the comparative comparison.

Code (taken from a more complex custom validator , one-third down):

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 && actualPropertyValue.Equals(Value);
    case Comparison.IsGreaterThan:
      // THIS LINE FAILS BECAUSE actualPropertyValue DOESN'T IMPLEMENT IComparable 
      return actualPropertyValue != null && (actualPropertyValue.CompareTo(Value) > 0); 
    // The rest of the comparison cases go here...
    default:
      throw new Exception("Comparison value is not defined");
  }
}

Static Helper Extensions:

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;
}
+5
source share
2 answers

It looks like you should just distinguish actualPropertyValuefrom IComparable:

IComparable comparable = (IComparable) actualPropertyValue;
return comparable != null && comparable.CompareTo(Value) > 0;

Please note that here you are curious to use the word "generic". If you made it general, you could write:

private bool IsRequired<T>(T actualPropertyValue) where T : IComparable

Then you do not need a throw.

+10
source
int MyCompare (object a, object b)
{
   var ac = a as IComparable;
   var bc = b as IComparable;

    if (ac == null || bc == null)
       throw new NotSupportedException();

    return ac.CompareTo(bc);
 }
+1
source

All Articles