C# - Designing classes using inheritance and operator overloading
<p>I have two classes which represent a special kind of numeric value. Let's call one "Value" and one "Fraction"; Fraction consists of a numerator and denominator of type Value. Because these are numeric values, operator overloading (+ - * /) makes a lot of sense. Given the nature of Value, division returns a Fraction. Operations can be performed with a mix of Values and Fractions.</p>

<p>Currently, I have just defined an implicit cast operator from Value to Fraction (and an explicit one from Fraction to Value, although I'm not using it), and am not using any sort of inheritance.</p>

<p>I am wondering if there is any "elegant" way to define both in terms of an abstract base class that defines the set of operations that are available, and calls the appropriate operation. Efficiency is a concern. I'd rather only use Fraction when necessary, and would rather not have to define more complex operations for both cases separately when they can be expressed using the same syntax.</p>

<p>One way I can see is doing something like the following for each operation, but I'm wondering if there are any better ways to do this?</p>

<pre><code>    public static AbstractValue operator *(AbstractValue a, AbstractValue b)
    {
        Value valA = a as Value;
        Value valB = b as Value;
        if(valA == null)
        {
            Fraction fractA = a as Fraction;
            if(valB == null)
            {
                Fraction fractB = b as Fraction;
                return fractA * fractB;
            }
            return fractA * valB;   
        }
        if(valB == null)
        {
                Fraction fractB = b as Fraction;
                return valA * fractB;
        }
        return valA * valB;
    }
</code></pre>
