3

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?

1
  • 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." Commented Aug 23, 2016 at 22:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Can't really decompile it since it's a .NET object, namely PointF, which is also sealed. So in other words, there's no workaround?
@Maurdekye You would never need to decompile a .NET object. .NET provides their source code publicly.
@Servy good point. Gonna change the text a little to reflect that.
Well that doesn't really help me, since I can't just rely on running my program on a custom version of .NET C#.
That seems like quite overkill for a simple convenience option. I think I'll just stick with my extension methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.