#400 – Overloading Binary Operators

You can overload any of the following binary operators: +, -, *, /, %, &, |, ^, <<, >>.  A binary operator is an operator applied to two operands.

For example, assume we have a Dog class that has the following bool properties: BarksALot, LikesBalls and Sheds.  We might implement the & operator for the Dog class so that we get a new Dog instance with all of the boolean properties AND’d together.

        public static Dog operator &(Dog d1, Dog d2)
            Dog newDog = new Dog(string.Format("{0} & {1}", d1.Name, d2.Name), 0);

            newDog.BarksALot = d1.BarksALot & d2.BarksALot;
            newDog.LikesBalls = d1.LikesBalls & d2.LikesBalls;
            newDog.Sheds = d1.Sheds & d2.Sheds;

            return newDog;

We can now apply this operator to two Dog instances.

            Dog kirby = new Dog("Kirby", 13);
            kirby.LikesBalls = true;
            kirby.BarksALot = true;

            Dog jack = new Dog("Jack", 10);
            jack.Sheds = true;
            jack.BarksALot = true;

            Dog newguy = kirby & jack;


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: