Tuesday, 3 March 2009

Operator, can you connect me to 555 Coolsville?

I’ve admired the operator keyword from afar for some time, the ability to overload operators and conversions is pretty wicked. It wasn’t until this morning that I had a requirement, so I’ve had a little play, in order to understand the basics.

My first experiment was very basic, my intention was to create a class that I can add together using the + operator. The code is below.

public class Account {
 public int Balance { get; set; }

 public static int operator + (Account a, Account b) {
   return a.Balance + b.Balance;
 }
}

var a = new Account { Balance = 5 };
var b = new Account { Balance = 5 };

int totalBalance = a + b; // 10

Now I happen to think that is pretty smart. My example was very basic, but think of all of the calculations that could be encapsulated within an operator overload. Within this framework you could calculate multiple property values and even output to a secondary custom class representing a balance sheet.

This last example was created to understand the relationship between calculations involving more than two instances of a class. Before I continue, I realise there are already short cuts in place to quickly create Generic lists. This example overloads the % operator to allow the quick creation of Generic lists. What is particularly interesting is that you can describe the relationships between your class and any other class that it may encounter.

public class Account {
 public int Balance { get; set; };

 public static List operator %(Account a, Account b) {
  return new List {
   a,
   b
  };
 }

 public static List operator %(List a, Account b) {
  a.Add(b);
  return a;
 }
}

var a = new Account { Balance = 5 };
var b = new Account { Balance = 5 };
var c = new Account { Balance = 6 };

(a % b % c).Count; // 3

Imagine the example above returning a custom collection or another object that allowed you to query the three accounts simultaneously for balances and other financial totals.

Twitter Updates