I'm not sure whether to classify this as a tip or bad advice: It's possible to redefine the operators (e.g. !, =, ++) used with a class. That doesn't mean it's a good idea. As I discussed in an earlier tip, the differences in using equality tests between C# and VB (and, within a language, the differences between the equals operator and the Equals method) probably create enough confusion without you assigning an arbitrary meaning to =/== for a particular class. But having said that…
Let's say you have some class that switches between two states: A Customer class that can be creditworthy or not creditworthy; a Service that switches between being "in" or "out" of service; a Product that is in-stock or out-of-stock. You can have a property that allows you to control this:
Dim cust As New Customer("A123")
cust.Creditworthy = False
To toggle between the two states, you could use this code:
cust.CreditWorthy = Not cust.Creditworthy
But it might be nice to just do this to toggle the Creditworthy property:
cust = Not cust
Before showing how to implement this, let me point out my chief objection: How would anyone reading your code or using your Customer object know what the Not operator is doing?
But if you want to do it, you add a shared/static Operator method to your class with the name Not. This Operator method should accept and return the object that it's part of (if you wanted to redefine the + operator, you'd add an Operator method called +). That method will be passed the object that the operator is being used on so that you can modify the object if you wish. Implementing my state-switching code would look like this:
Public Shared Operator Not(Cust As Customer) As Customer
Cust.Creditworthy = Not Cust.Creditworthy
In C#, the code looks like this:
public static Customer operator !(Customer cust)
cust.Creditworthy = !cust.Creditworthy
I can now toggle the creditworthiness of a Customer object in C# like this:
cust2 = !cust;
Postfix and prefix conventions are also honored with operators that support it. The primary difference in overriding binary operators (e.g. +, -) is that your operator method is passed two parameters: the object on either side of the operator.
Like I said: I'm not sure if this is a tip or bad advice, but I had a client ask me how to do it so people do seem to care.
Posted by Peter Vogel on 10/16/2012 at 1:16 PM