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:
return actualPropertyValue != null && (actualPropertyValue.CompareTo(Value) > 0);
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;
}
source
share