Reputation: 3677
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
Reputation: 4634
Three options:
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