What are Operators in C#?
Operators are language symbols that specify which operations to perform in an expression. If you are a programmer, you are familiar with the usual arithmetic and logic operators, such as the "+" and "-" for adding and subtracting, and the "&" for (anding) boolean comparisons.
What do you mean by Overloading?
Since most classes aren't primarily concerned with such arithmetic or logical evaluation, C# allows classes to "overload" these operators for their own custom use.
The following example shows how to overload the "+" and "-" operators for use in a hypothetical Order class. The goal is to utilize "+" for adding an item to an order, and "-" for removing an item from an order.
public class Order
//other details omitted
public static Order operator +(Order order, OrderItem orderItem)
public static Order operator -(Order order, OrderItem orderItem)
Here is a test (NUnit) to illustrate the intended usage (remember x += y is shorthand for x = x + y):
public void AddOrderItem()
Order order = new Order();
OrderItem orderItem = new OrderItem(15);
order += orderItem;
Assert.That(order.OrderItems.Count == 1);
Overloading Operator Overloading
If you had tried to use the overloaded operator defined above with a different "target" class, such as adding a shipping charge to an order, (i.e.: order += shippingCharge) you would have received the error "Operator '+=' cannot be applied to operands of type 'Order' and 'ShippingCharge'
But, if you indeed want the "+" operator to also allow adding a ShippingCharge object, you can define that behavior as well. And it's a great way to illustrate what I call "Overloading Operator Overloading", a.k.a. O3
*grin*. As such, the signature of the additional overloaded "+" would be:
public static Order operator +(Order order, ShippingCharge shippingCharge)
In The Wild
In the .Net Framework itself, you have probably seen the "+" (and therefore the "+=") operator overloaded for the purpose of adding a event handler for an event.
btnSubmit.Click += new System.EventHandler(btnSubmit_Click);
Many (but not all) operators can be overloaded. You can view the list at MSDN
. Included in this list are cast operators "()" which give you control over the casting behavior
of your classes. One example would be converting a Farenheit object to a Celsius object (example via MSDN docs):
Farenheit f = new Farenheit(100.0f);
Celsius c = (Celsius)f;
With the overloaded casting operator found in the Celsius class:
public static explicit operator Celsius(Farenheit f)
return new Celsius((5.0f/9.0f)*(f.degrees-32));
I must admit that generally the "syntactic shorthand" that overloading operators affords you is more of a nice-to-have than a problem-solver. However, I think that there is definitely some untapped potential with the casting operators, in particular.
If you found this post helpful, please "Kick" it so others can find it too: