Friday, May 10, 2013

Operator Overloading and Overriding ToString()

Operator Overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type. Also to note, assignment operator "=" cannot be overloaded in C#.
Similarly for the complex objects there is also need to override ToString() method.

Following is a simple example of operator overloading "+", "++", "==", "!=" and method overriding with a struct with two Integer variables. There is a small observation when operator "==" is overloaded user need to overload "!=" operator also, this is mandatory else user will receive compilation error.
public struct Test    
{
    public int iCnt1;
    public int iCnt2;
    public Test(int iD1, int iD2)
    {
        this.iCnt1 = iD1;
        this.iCnt2 = iD2;
    }
    public static Test operator +(Test T1, Test T2)
    {
        return new Test(T1.iCnt1 + T2.iCnt1, T1.iCnt2 + T2.iCnt2);
    }
    public static Test operator ++(Test T1)
    {
        T1.iCnt1++;
        T1.iCnt2++;
        return T1;
    }
    public override bool Equals(object Obj)
    {
        Test other = (Test)Obj;
        return (this.iCnt1 == other.iCnt1 && this.iCnt2 == other.iCnt2);
    }
    public static bool operator ==(Test T1, Test T2)
    {
        return T1.Equals(T2);
    }
    public static bool operator !=(Test T1, Test T2)
    {
        return !(T1 == T2);
    }
    public override string ToString()
    {
        return (string.Format("iD1 = {0}, iD1 = {1}", iCnt1, iCnt2));
    }
}

To understand how it works following is the sample console application and output
class Program
{
    static void Main(string[] args)
    {
        Test TT1 = new Test(4, 5);
        Test TT2 = new Test(10, 15);
        Test TT3 = TT1 + TT2;
        Console.WriteLine("Object 1 ({0}) + Object 2 ({1})", TT1, TT2);
        Console.WriteLine("Addition Result of + {0}", TT3);
        TT3++;
        Console.WriteLine("Addition Result of ++ {0}", TT3);
        if (TT3 != (TT1 + TT2))
            Console.WriteLine("Validation Result of != is True", TT3, TT1, TT2);
        TT3 = TT1 + TT2;
        if (TT3 == (TT1 + TT2))
            Console.WriteLine("Validation Result of == is True", TT3, TT1, TT2);
        Console.ReadLine();
    }
}

Output
Object 1 (iD1 = 4, iD1 = 5) + Object 2 (iD1 = 10, iD1 = 15) 
Addition Result of + iD1 = 14, iD1 = 20                     
Addition Result of ++ iD1 = 15, iD1 = 21                    
Validation Result of != is True                             
Validation Result of == is True                             

No comments:

Post a Comment