Operator overloading in C#

C# allows you to overload certain operators. The figure below shows a table of overloadable operators.

Overloadable operators in C#

Suppose there is a BankAccount class which contains a Number property and a Balance property. The + (addition) operator can be overloaded to combine two BankAccount instances and to return a new BankAccount instance with the combined balances. This is demonstrated in the following console application.

BankAccount class

    class BankAccount
    {
        public int Number { get; set; }
        public double Balance { get; set; }

        public BankAccount(int number, double balance)
        {
            this.Number = number;
            this.Balance = balance;
        }

        // Overload the + operator
        public static BankAccount operator +(BankAccount firstAccount, BankAccount secondAccount)
        {
            Random r = new Random(DateTime.Now.Millisecond);
            return new BankAccount(r.Next(), firstAccount.Balance+secondAccount.Balance);
        }

        public override string ToString()
        {
            return "Number: " + this.Number +
                    "\nBalance: " + this.Balance + "\n";
        }

    }

The main program

    class Program
    {
        static void Main(string[] args)
        {
            BankAccount firstAccount = new BankAccount(1, 200);
            BankAccount secondAccount = new BankAccount(2, 400);

            // Combine two BankAccount instances
            BankAccount combinedAccount = firstAccount + secondAccount;

            Console.WriteLine(firstAccount);
            Console.WriteLine(secondAccount);
            Console.WriteLine(combinedAccount);
            Console.ReadLine();
        }
    }

Output:

Number: 1
Balance: 200

Number: 2
Balance: 400

Number: 184538645
Balance: 600

A random account number has been used in the combined BankAccount instance.

This entry was posted in C# and tagged , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?