Maurdekye
Maurdekye

Reputation: 3677

C# - Operator Overload Extensions

C# is a versatile language; it gives you a lot of freedom to manipulate your own and existing classes. You can overload operators to use + and * with custom objects, and you can extend existing objects to add new methods to them. But for some reason, C# doesn't let you do operator overloads as extensions to existing classes. Why is this? Is there a workaround, or if I want to write operator overloads for existing classes then should I just make .Plus() and .Times() extension methods?

Upvotes: 3

Views: 1777

Answers (1)

Xavier J
Xavier J

Reputation: 4634

Three options:

  1. Subclass them, and write overloads for the subclass
  2. Use Microsoft's publicly available source code for the respective classes (or decompile them), and write your overloads. This is not maintainable in the long term, or necessarily easy, but it will work.
  3. Stick with your extension methods.
  4. Conversion operators between your class and a "clone" class as described below.

In the comments, the OP has specifically mentioned using System.Drawing.PointF. What I've done in the past, with sealed classes like this, is to develop a second similar class using the .NET source as described above. Let's call this second class MyCustomPointF. I can write operators for my new class. But what I'm also going to add is what's called an implicit conversion operator that helps the compiler to convert an instance of my class back to a System.Drawing.PointF instance when I need it (without calling an external conversion function). It's not perfect, but it's an option.

Upvotes: 2

Related Questions