Thursday, August 20, 2015

Operator Overloading in C#

Introduction

What happens when a natural disaster causes a backlog on 911 calls? Operator overload! Hahaha, I slay me. Ok so maybe there's a different form of operator overloading I'd like to discuss today, and it's the kind where you can overload the operators of the c# language. Want to redefine what == means for your class? Have at it. Want to add together two widgets and get a resulting mutant widget of doom? Go nuts I say! Operator overloading lets you redefine what most of the c# language operators mean for your class.



Here is the code, it is written using VS2013 Community Edition.

Example

I'm going to let an example do the talking for just a minute here:

using System;
using System.Linq;

namespace BlogOperatorOverload
{
    public class Monster
    {
        public string MonsterType { get; set; }
        public string Name { get; set; }

        public override string ToString()
        {
            return String.Format("{0}::{1}", MonsterType, Name);
        }

        public static Monster operator+(Monster monster1, Monster monster2)
        {
            if ((monster1.MonsterType.Equals("dragon", StringComparison.OrdinalIgnoreCase) && 
                monster2.MonsterType.Equals("man", StringComparison.OrdinalIgnoreCase)) || 
                (monster1.MonsterType.Equals("man", StringComparison.OrdinalIgnoreCase) && 
                monster2.MonsterType.Equals("dragon", StringComparison.OrdinalIgnoreCase)) 
                )
                return new Monster() { MonsterType = "Dragon-Man", Name = "Trogdor!" };
            else
                return new Monster() { MonsterType = monster1.MonsterType + "_" + monster2.MonsterType, Name = String.Join("", monster1.Name.Reverse()) + String.Join("", monster2.Name.Reverse()) };
        }
    }
}


So this first part of the sample is a class named Monster. It has 2 properties that define what it is to be a monster, an overridden ToString method that we'll use to check our output in a little bit, and most importantly it overloads the "+" addition operator. See the syntax of that? it's pretty easy; "public static [returntype] operator[operator_to_overload](params)". In this case I'm adding instance monster1 to instance monster2. I put some interesting logic in this method to handle a special edge case, and in the else I put the catch-all addition of 2 monsters. All we're doing here is creating a new resulting Monster instance that has a MonsterType and Name. Pretty cool huh? This has nothing to do with addition, but we can now add together 2 instances of the Monster class as though they were numbers! Let's see that part of the example now:

using System;

namespace BlogOperatorOverload
{
    class Program
    {
        static void Main(string[] args)
        {
            var aMan = new Monster() { Name = "Timmy", MonsterType = "Man" };
            var aDragon = new Monster() { Name = "Puff", MonsterType = "Dragon" };
            var troggy = aMan + aDragon;
            Console.WriteLine(troggy.ToString());
            var aBear = new Monster() { Name = "Billy", MonsterType = "Bear" };
            var aTiger = new Monster() { Name = "Tina", MonsterType = "Tiger" };
            var qtf = aBear + aTiger;
            Console.WriteLine(qtf.ToString());
            Console.ReadKey();
        }
    }
}


Another simple bit of code. We first declare an instance of Monster named aMan, declare another one named aDragon, and then add aMan to aDragon to get a 3rd instance variable named troggy. Any guesses as to the output of this line? If you feel like cheating the answer is a little further down the page.

Now we create an instance of Monster named aBear, another named aTiger, and add them together. Go ahead, be wild, guess what the output will be!

Or just cheat and check out this screenshot:

Yes that's right folks, it's really that easy to redefine operators in c#. When would you want to use this? Hell if I know, I haven't actually found a practical use for it yet. Drop me a line if you find one!

What's Next?

Create your own samples and play with some of the other overloadable operators. There's a link down in the Resources section that lists the overloadable operators.

Resources

Operator Overloading Tutorial
Overloadable Operators

No comments:

Post a Comment