IArithmeticallyOperable

This interface defines the established arithmetic operations that a value type or class implements to perform arithmetic operations with other instances.
Then, if an object type implements IArithmeticallyOperable it means that the type can perform arithmetic operations using other object as second operand.

The members of this interface are:
Member Description
Add Sums the current instance and the specified object and return the result.
Subtract Subtracts the current instance and the specified object and return the result.
Multiply Multiplies the current instance and the specified object and return the result.
Divide Divides the current instance and the specified object and return the result.
Mod Divides the current instance and the specified object and return the reminder value.


Next implementation defines an integer number type that implements IArithmeticallyOperable.

public struct Integer : IArithmeticallyOperable
{
    private int value;
    public int Value
    {
        get { return value; }
    }

    public Integer(int value)
    {
        this.value = value;
    }

    public object Add(object obj)
    {
        if (obj is Integer)
        {
            return this.value + ((Integer)obj).Value;
        }
        throw new InvalidCastException();
    }

    public object Subtract(object obj)
    {
        if (obj is Integer)
        {
            return this.value - ((Integer)obj).Value;
        }
        throw new InvalidCastException();
    }

    public object Multiply(object obj)
    {
        if (obj is Integer)
        {
            return this.value * ((Integer)obj).Value;
        }
        throw new InvalidCastException();
    }

    public object Divide(object obj)
    {
        if (obj is Integer)
        {
            return this.value / ((Integer)obj).Value;
        }
        throw new InvalidCastException();
    }

    public object Mod(object obj)
    {
        if (obj is Integer)
        {
            return this.value % ((Integer)obj).Value;
        }
        throw new InvalidCastException();
    }

    public override string ToString()
    {
        return value.ToString();
    }
}

Last edited Jul 26, 2013 at 3:19 AM by rathmA, version 1

Comments

No comments yet.