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?
-
To be clear, extension methods don't add new methods to existing objects. They allow calls to static methods with a first parameter of a type to be optionally called with the "dot operator" syntax on instances of classes that inherit from the type. It's just "syntactic sugar."Tom Blodget– Tom Blodget2016-08-23 22:26:02 +00:00Commented Aug 23, 2016 at 22:26
1 Answer
Three options:
- Subclass them, and write overloads for the subclass
- 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.
- Stick with your extension methods.
- 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.