Operator Overloading with Implicit and Explicit Casts in C#

0 comments
Its been a very common mistake of not declaring implicit and explicit cast operator overloads while working with data types which might take part in some calculations in long run. Many of the developers don't know why we use checked or unchecked while doing calculations. This post is an article on how you can use Cast overloads to get your job done easily when you require your type to take part in arithmetic operations and casts to arithmetic data types.

Let us explain the concept using an example. Declare a class that would take Feet and inches in one single type. C# doesn't expose such type to us. So let us create one for us to demonstrate the concept.

public class Finch
    {
        private int feet;
        private int inch;

        public int Feet
        {
            get { return this.feet; }
            set
            {
                this.feet = value;
            }
        }
        public int Inches
        {
            get { return this.inch; }
            set
            {
                if (value > 11)
                {
                    this.feet += (value / 12);
                    this.inch = (value % 12);
                }
                else
                    this.inch = value;
            }
        }
        public override string ToString()
        {
            return string.Format("{0}''{1}'", this.Feet, this.Inches);
        }
    }

So you can see there is a declared class Finch which has two members Feet and Inches. The class is used to hold. As a matter of fact, the value of inches cannot be made over 11. So in the setter of inches, we strip the values which is greater than 11 to add up to the feet. So that we always get the proper value for Feets and inches.

Lets take the class a bit further.
Download Source Code - 30KB



Operator OverloadingWe all might somehow know what operator overloading is. Overloading an operator means extending the nature of a normal operator to make it work little more of what it is capable of doing so. Lets overload the operator + for our class Finch.
public static Finch operator +(Finch oldvalue, dynamic value)
{
    checked
    {
        if (value is Finch)
        {
            Finch newValue = value as Finch;
            oldvalue.Feet += newValue.Feet;
            oldvalue.Inches += newValue.Inches;
            return oldvalue;
        }
        else //try if its a fraction
        {
            decimal d;
            try
            {
                d = Convert.ToDecimal(value); // when convertion fails it throws exception in runtime
            }
            catch
            {
                throw;
            }
            oldvalue.Feet += Convert.ToInt32(Decimal.Truncate(d));
            var thisval =  Math.Abs(oldvalue.feet - d);
            oldvalue.Inches += (int)(.83f / Convert.ToSingle(thisval));
            return oldvalue;
        }
    }
}
In the above code you can see we have overloaded the + operator to take almost everything in compile type, as we defer the check to  run time using dynamic keyword.  If you are not in C# 4.0, you can easily replace it to any of the known data types.

You can see we wrapped the entire code within a checked block. This will ensure that the block throws OverflowException whenever the conversion produces Arithmetic Overflows. If you dont want this to happen, you can either wrap the checked block into a try-Catch block to ensure you handle the OverflowException within it.

As we overload the + operator with dynamic variable, we first check whether the dynamic variable is an object of Finch. If so, we just add up the feet and inches of the new Finch variable.
Otherwise we check if the value is convertible to a Decimal. This will also ensure that the variable passed within the block can take part in arithmetic operations too.
Finally we convert the decimal part to add up to feets and the fraction part to the inches.  By this way you can easily overload operators for your own types.

READ MORE >>
http://www.abhisheksur.com/2010/07/operator-overloading-with-implicit-and.html

0 comments: