Thursday, October 15, 2009

Operator Overloading for Dummies

Hi,

It's been a while I have blogged about anything. And I found myself replying to a question regarding "Operator Overloading" in a User Group in Orkut.

Here's what the requirement was,

i have just started learning object oriented concepts and was wondering if some one could explain me using a practical real world example the use of operator overloading.

Disclaimer(read before you go any further):
the guy also happened to be an Indian. And in India, after the God, there's only one thing people worship, which is "Cricket"!! so, the Example that I have used is of course as you guessed right, it's definitely related to Cricket!!

Here's my reply to him, but be forewarned, this is strictly meant to help the Dummies like ME!! so please try not to leave any sarcastic comments please ;)

Here we Go!!!

I am pretty sure you can find out a lot of examples if you search for "Operator Overloading C#" in Google.

Apart from that, if you want a very high level understanding how Operator Overloading is used and why, I was thinking about, in a way Funny and not so convincingly real life but easy to understand example.

Say someone decides to create a game of Cricket, and he wants to give the user the ability to create a new player of his own, out of the existing players which are already in the game.

like, the user wants to create a super Player whose main skill is "batting", and he should have the strike rate which is average of Sachin and Lara both

If we try to put this particular requirement in terms of Object Oriented Programming.

There should be Classes like "Player", with following implementation,

class Player
{
public string name;
public double strikeRate;
public Player()
{
}

public Player(string Name, double StrikeRate)
{
name = Name;
strikeRate = StrikeRate;
}

//here's where Operator Overloading is done
public static Player operator +(Player p1,Player p2)
{
Player temp = new Player();
temp.strikeRate = (p1.strikeRate + p2.strikeRate) / 2;
return temp;
}
}

so now, as you know mostly + operator is used for addition.
but here we can Overload + operator for Player Class, so that when you type

Player playerSachine = new player("Sachine", 85.74);
Player playerLara = new player("Lara", 79.51);
Player SuperPlayer = new Player();

SuperPlayer = PlayerSachin + PlayerLara;

This will set the SuperPlayer's strikeRate which is the average of both the Great Players.
Which is 82.63. Here you can see the use of "Operator Overloading". So without this particular method

public static Player operator +(Player p1,Player p2)

in Player class, it would have been a compiler error at the line

SuperPlayer = PlayerSachin + PlayerLara;

hope it helps to someone who's starting up with OOP.

Happy Coding!!

No comments: