Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is overloading operators in C# actually good practice? [closed]

Being new to C#, I am aware of the purpose and uses of operator overloading, and I can see how it's sometimes elegant in very specific cases such as negating a value object to negate all of its fields at once, however such things can always be done with simple, speaking methods. Is there some standard I can use as a guideline, when or whether to overload operators or when to simply use a method? I couldn't find anything like that, so is it just a matter of taste/programming paradigm/style?

like image 694
Andreas Hartmann Avatar asked Apr 21 '17 17:04

Andreas Hartmann


2 Answers

This is the closest thing I have found to operator overloading guides of any sort: MSDN operator overload

I came to C# from a C++ background where operator overloads were part of the norm. The problem with C# that makes it less useful is that all objects are references. Because of this you cannot overload the = operator which, in my mind would be the most useful operator to overload for complex objects. That being said, writing an extension method can achieve the same goal with the same code.

And as noted in the comments, I have also been working in C# for nearly 10 years and have yet to see someone overload an operator.

like image 125
Chris Bartlett Avatar answered Oct 02 '22 13:10

Chris Bartlett


The cases where I want to use operator overloading are the ones where C# won't allow its use - in extension methods. It would certainly be nice to overload TimeSpan with operator/ and perhaps operator* but you can't have extension operators.

Otherwise I think it only makes sense when creating algebraic types or (perhaps) a new tiny language that uses chained operators (ala C++ output operators). E.g. I could see a variation of Linq based around operators being interesting.

like image 30
NetMage Avatar answered Oct 02 '22 11:10

NetMage